今天主要分享一下JDBC的工具类,自己写的不是很完善。其中每个地方都有注释。工具类可以帮助我们更简单的调用其方法和扩展。
public class JdbcUTIL {
private JdbcUTIL() {
}//私有构造,不可继承
private static JdbcUTIL ju = new JdbcUTIL();
public static JdbcUTIL getinsatnce() {
return ju;
}//饿汉模式,统一的访问
private static List<Connection> pool;//连接池
private static final int MAX_SIZE = 10;//常量,设置为10,连接池最大容量
static {
pool = Collections.synchronizedList(new ArrayList<>());//变为线程安全的,通过sollections工具类
try {
Connection conn;
Class.forName("com.mysql.cj.jdbc.Driver");//加载驱动
for (int i = 0; i < 3; i++) {//类加载时自动创建三个连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/库名?serverTimezone=UTC", "用户名",
"密码);
pool.add(conn);
}
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException {//获取连接,如果池中剩余则取,无则新建
Connection conn;
if (pool != null && pool.size() > 0) {
conn = pool.remove(pool.size() - 1);
} else {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/库名?serverTimezone=UTC", "用户名",
"密码);
}
return conn;
}
public void close(ResultSet rs, PreparedStatement ps, Connection conn) throws SQLException {//关闭连接资源
try {
if (rs != null)
rs.close();
} finally {
try {
if (ps != null)
ps.close();
} finally {
reseletConn(conn);//前往释放方法
}
}
}
private void reseletConn(Connection conn) throws SQLException {//如果连接池满,则close()释放,如果不满则归入池中
if (conn != null) {
if (pool.size() < MAX_SIZE) {
pool.add(conn);
} else {
conn.close();
}
}
}
public PreparedStatement createPreparedStatement(Connection conn, String sql, Object... params)
throws SQLException {
PreparedStatement ps = conn.prepareStatement(sql);
if (params != null && params.length > 0) {//赋值问号占位符
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
return ps;
}
public ResultSet executeQuery(Connection conn, String sql, Object... params) throws SQLException {
PreparedStatement ps = createPreparedStatement(conn, sql, params);
return ps.executeQuery();//返回查询语句,结果集
}
public int executeUpdate(Connection conn, String sql, Object... params) throws SQLException {
PreparedStatement ps = createPreparedStatement(conn, sql, params);
return ps.executeUpdate();//返回增删改语句,被修改的行数
}
}