数据库操作整合成一个DBUtil,去除重复代码(如果报错,注意导包,导包应该导的是java.sql下的包)
2021/7/13 19:12:57
本文主要是介绍数据库操作整合成一个DBUtil,去除重复代码(如果报错,注意导包,导包应该导的是java.sql下的包),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
public class DBUtil {
private static final String DBDRIVER = "com.mysql.jdbc.Driver";
//注意这里的数据库名需要修改成你自己操作的数据库
private static final String DBURL = "jdbc:mysql://localhost:3306/movie?serverTimezone=GMT%2B8" +
"&characterEncoding=utf8&useUnicode=true&useSSl=false";
private static final String DBUSER = "root";
private static final String DBPASSWORD = "root";
//获取数据库连接对象
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//关闭资源连接
public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
if(rs != null) {
try {
rs.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//创建数据库操作对象(PreparedStatement对象)
public static PreparedStatement getPreparedStatement(Connection conn, String sql) {
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
} catch (Exception e) {
e.printStackTrace();
}
return pstmt;
}
//创建数据库操作对象(Statement对象)
public static Statement getStatement(Connection conn) {
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
return stmt;
}
//封装更新操作语句
public static int executeDML(String sql, Object...objs) {
int rows = 0;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
pstmt = getPreparedStatement(conn, sql);
for (int i = 0; i < objs.length; i++) {
pstmt.setObject(i + 1, objs[i]);
}
rows = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(null, pstmt, conn);
}
return rows;
}
}
这篇关于数据库操作整合成一个DBUtil,去除重复代码(如果报错,注意导包,导包应该导的是java.sql下的包)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-16ShardingSphere 如何完美驾驭分布式事务与 XA 协议?
- 2024-11-16ShardingSphere如何轻松驾驭Seata柔性分布式事务?
- 2024-11-16Maven资料入门指南
- 2024-11-16Maven资料入门教程
- 2024-11-16MyBatis Plus资料:新手入门教程与实践指南
- 2024-11-16MyBatis-Plus资料入门教程:快速上手指南
- 2024-11-16Mybatis资料入门教程:新手必看指南
- 2024-11-16MyBatis资料详解:新手入门与初级实战指南
- 2024-11-16MyBatisPlus资料:初学者入门指南与实用教程
- 2024-11-16MybatisPlus资料详解:初学者入门指南