通过JDBC连接数据库(三)
程序员文章站
2022-05-18 19:37:10
...
通过单例创建JDBCUtil
package com.huawei;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author zhangzhao
*
* 2012-2-17下午08:53:27
*/
public final class JDBCUtil2 {
private String url="jdbc:mysql://localhost:3306/jdbc";
private String user="root";
private String password="root";
private static JDBCUtil2 instance=null;
private JDBCUtil2()
{
}
public static JDBCUtil2 getInstance(){
if(instance==null){
//懒加载(延时加载,用的时候才去加载)
synchronized (JDBCUtil2.class) {
if(instance==null){
instance=new JDBCUtil2();//第一次加锁
}
}
}
return instance;
}
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, user, password);
}
public void free(ResultSet rs,PreparedStatement pStatement,Connection conn){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if(pStatement!=null)
pStatement.close();
} catch (Exception e2) {
// TODO: handle exception
}
finally{
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
推荐阅读