package Base;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//不可被继承的工具类
public final class JdbcUtilsSingleton {
//私有化成员变量,防止影响其他类共有的变量
private String url = "jdbc:mysql://127.0.0.1:3306/jdbc";
private String username = "root";
private String password = "123456";
private static JdbcUtilsSingleton instance=null;
//私有化构造函数,确保不被外部实例化
private JdbcUtilsSingleton(){
}
/**
* 考虑到并发需要枷锁
* @return
*/
public static JdbcUtilsSingleton getInstance(){
if(instance == null){
synchronized(JdbcUtilsSingleton.class){
if(instance == null){
instance = new JdbcUtilsSingleton();
}
}
}
return instance;
}
//加载JVM时只创建一次连接
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获取连接
public Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, username, password);
}
//规范释放资源方法
public 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 ex){
ex.printStackTrace();
}finally{
try{
if(conn != null)
conn.close();
}catch(SQLException em){
em.printStackTrace();
}
}
}
}
}