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一次
* 单例模式不使用静态的
* A0102JdbcUtilsSingletonRetard
* 意思:jdbc工具类,单例,延迟加载就是用到的时候再new
* @author Administrator
*
*/
public final class A0103JdbcUtilsSingletonRetard {
private String url = "jdbc:mysql://127.0.0.1:3306/jdbc";
private String user = "root";
private String password = "root";
/**
* 预初始化
*/
private static A0103JdbcUtilsSingletonRetard instance = null;
private A0103JdbcUtilsSingletonRetard(){
}
/**
* 加锁模式,双重检查,防止重复的new
* @return
*/
public static A0103JdbcUtilsSingletonRetard getInstacce(){
if(instance==null){
synchronized (A0103JdbcUtilsSingletonRetard.class) {
if(instance==null){
instance = new A0103JdbcUtilsSingletonRetard();
}
}
}
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连接数据库单例延迟加载

最新推荐文章于 2022-09-22 13:09:47 发布
