public class JdbcUtil {
private Connection con = null;
private PreparedStatement ps = null;
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Driver接口实现类被注册了");
}
//封装Connection对象创建细节
public Connection createCon(){
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","123456");
} catch (SQLException throwables) {
throwables.printStackTrace();
System.out.println("Connect对象创建失败");
}
return con;
}
//封装PreparedStatement对象创建细节
public PreparedStatement createStatement(String sql){
Connection con = createCon();
try {
ps = con.prepareStatement(sql);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return ps;
}
//封装PreparedStatement对象与Connection对象销毁细节
public void close(){
if (ps!=null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con!=null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//封装PreparesStatement对象与Connection对象与ResultSet对象销毁细节
public void close(ResultSet rs){
if (rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
close();
}
}
JDBC封装
本文介绍了一个名为JdbcUtil的Java类,用于封装数据库连接、PreparedStatement操作及资源关闭。它简化了与MySQL数据库的交互,展示了如何创建Connection、PreparedStatement并管理其生命周期。
摘要由CSDN通过智能技术生成