package utils;
import java.sql.*;
/**
* @author zzw
* @create 2020/11/17-16:15
*
* jdbc工具类:简化jdbc编程
*/
public class DBUtil {
/**
* 工具类的构造方法都是私有的。
* 因为工具类当中的方法都是静态的,不需要new对象,直接采用类名调用
*
*/
private DBUtil(){}
//静态代码块在类加载时执行,并且只执行一次
static {
try {
//Class.forName("com.mysql.jdbc.Driver"); 每次这个都报错,明明导入了还是错
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*获取数据库连接对象
* @return 连接对象
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
/*
Class.forName("com.mysql.jdbc.Driver");
当我们在一个程序中调用了两次这个方法,我们没有必要每次调方法都执行这个,
就会走两次注册驱动,注册驱动我们只需要走一次就够了
*/
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","a");
return null;
}
/**
* 关闭资源
* @param conn 连接对象
* @param ps 数据库操作对象
* @param rs 结果集
*/
public static void close(Connection conn, Statement ps, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
JDBC学习----12--jdbc工具类的封装(每次都写6步太麻烦)
最新推荐文章于 2021-03-06 15:34:28 发布