`
it_liuyong
  • 浏览: 98135 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
jdbc单例模式
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(); 
    } 
   } 
  } 
} 
} 

Global site tag (gtag.js) - Google Analytics