一、设计思想
JDBCUtil工具类提供Connection
类的获取,Statement
、PreparedStatement
、ResultSet
则是在其他类中创建,在此类中传入其参数关闭。
二、JDBCUtil工具类
提供了两个实例方法:
- 获得链接的
getConnection()
- 关闭链接的
closeConnection(Connection con)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCUtil {
// mysql驱动
private final String JDBC_DRIVER_8UP = "com.mysql.cj.jdbc.Driver";
// 名为ordermanagement的数据库名url
private final String DB_URL_8UP = "jdbc:mysql://localhost:3306/ordermanagement?useSSL=false&serverTimezone=UTC&&allowPublicKeyRetrieval=true";
// 用户名
private final String user="root";
// 密码
private final String password="1234";
// 获得链接
public Connection getConnection() throws Exception {
Class.forName(JDBC_DRIVER_8UP);
return DriverManager.getConnection(DB_URL_8UP, user, password);
}
// 关闭链接
public void closeConnection(Connection con) throws Exception {
if(con!=null) {
con.close();
}
}
// 关闭Statement
public void closeStatement(Statement stmt) throws Exception {
if(stmt!=null) {
stmt.close();
}
}
// 关闭PreparedStatement
public void closePreparedStatement(PreparedStatement pstmt) throws Exception {
if(pstmt!=null) {
pstmt.close();
}
}
// 关闭PreparedStatement
public void closeResultSet(ResultSet rs) throws Exception {
if(rs!=null) {
rs.close();
}
}
}
三、使用
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Customer {
public static void main(String[] args) {
JDBCUtil jdbcUtil = new JDBCUtil();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = jdbcUtil.getConnection();
stmt = con.createStatement();
String sql = "SELECT * FROM customer";
rs = stmt.executeQuery(sql);
if(rs.next()) {
System.out.println(rs.getInt("account"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 及时关闭使用到的con、stmt、pstmt、rs
jdbcUtil.closeConnection(con);
jdbcUtil.closeStatement(stmt);
jdbcUtil.closeResultSet(rs);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/*
110001
*/