package jdbc.com.bjpwnd.jdbc.util;

import java.sql.*;

/*
* JDBC工具类简化JDBC编程。
* */
public class DBUtil {
/*
* 工具类中的方法都是私有的,因为工具类当中的方法都是静态的,不需要new对象,直接采用类名调用*/
private DBUtil(){};
//静态代码块只在类加载中执行并且只执行1次
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
*获取数据库对象
* @return 连接对象
* @throw SQLException
* */
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/First","root","xiuluoA1");
}

/**
* 关闭资源
* @param conn 连接对象
* @param stmt 数据库操作对象
* @param rs 结果集
*/
public static void close(Connection conn, Statement stmt,ResultSet rs){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}

posted on 2021-09-22 23:29  比企苦  阅读(32)  评论(0编辑  收藏  举报