JDBC的单例模式

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
*
*
*
*/
public final class JDBCSingleton {

private String url = "jdbc:mysql://localhost:3306/jdbc";

private String username = "root";

private String password = "root";

// 构造函数私有
private JDBCUtilSingle() {
}

// 构造私有实例
private static JDBCUtilSingle instance = null;

public static JDBCUtilSingle getInstance() {
//延迟加载
if (instance == null) {
//加锁 防止线程并发
synchronized (JDBCUtilSingle.class) {
//必须有的判断
if(instance == null){
instance = new JDBCUtilSingle();
}
}
}
return instance;
}

// 注册驱动
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}

// 获取连接
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(instance.url, instance.username,
instance.password);
}

// 释放资源
public static void free(ResultSet rs, Statement stmt, Connection conn) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}