您的位置:首页 > 其它

一个简单的JDBC模板类

2020-02-03 00:28 369 查看
/**

* @author 千禧
* @version 创建时间:2019年9月24日 下午9:02:10

*/
public class JdbcTest {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver");

connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true", "root", "password");
// 输入你的sql语句
String sql = "";

preparedStatement = connection.prepareStatement(sql);

preparedStatement.setInt( ?,?);

resultSet = preparedStatement.executeQuery();

while(resultSet.next()) {
//处理结果集
}

} catch (Exception e) {
e.printStackTrace();
}finally {
if(resultSet !=null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

if(preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

if(connection !=null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

注意:新版mysql的jar包需要的两个参数有丶矫情。这里列出来:

className = "com.mysql.cj.jdbc.Driver";

url = "jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";

//补充一下,如果是在xml文件中配置uri参数的话,需要写成如下的方式
uri = "jdbc:mysql://127.0.0.1:3306/dbname?useUnicode=true&characterEncoding=gbk&useSSL=false&serverTimezone=GMT%2B8&useSSL=false"

ok,就这样吧。以上就是一个建议的jdbc模板了。使用的时候别忘了导包。
最后记得关闭三个流。注意:先打开的后关闭。。

  • 点赞
  • 收藏
  • 分享
  • 文章举报
千禧0410 发布了11 篇原创文章 · 获赞 0 · 访问量 166 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: