package com.daqing.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 单例模式会有一个实例;会new一次
* 单例模式不使用静态的
* A0102JdbcUtilsSingletonBeforehand
* 意思:jdbc工具类,单例,预先初始化
* @author Administrator
*
*/
public final class A0102JdbcUtilsSingletonBeforehand {
private String url = "jdbc:mysql://127.0.0.1:3306/jdbc";
private String user = "root";
private String password = "root";
/**
* 预初始化
*/
private static A0102JdbcUtilsSingletonBeforehand instance = new A0102JdbcUtilsSingletonBeforehand();
private A0102JdbcUtilsSingletonBeforehand(){
}
public static A0102JdbcUtilsSingletonBeforehand getInstacce(){
return instance;
}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
public Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, user, password);
}
public void free(ResultSet rs, PreparedStatement ps, Connection conn){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
System.out.println("ResultSet关闭发生异常...");
} finally {
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
System.out.println("PreparedStatement关闭发生异常...");
} finally {
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
System.out.println("Connection关闭发生异常...");
}
}
}
}
}
}
}
jdbc连接数据库单例预先初始化
最新推荐文章于 2023-05-12 22:51:30 发布