java链接数据库单例_JDBC数据库单例配置

packagecom.hooy.util;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;/***

*@authorJDBC辅助类 用于构建数据库连接(采用单例模式)*/

public final classJDBCUtilSingle {//该url为缺省方式(省略主机跟端口)//完整为:jdbc:mysql//localhost:3306/test

static String url = "jdbc:mysql:///hooyplatform";static String name = "root";static String password = "1234";static Connection conn = null;private static JDBCUtilSingle jdbcUtilSingle = null;public staticJDBCUtilSingle getInitJDBCUtil() {if (jdbcUtilSingle == null) {//给类加锁 防止线程并发

synchronized (JDBCUtilSingle.class) {if (jdbcUtilSingle == null) {

jdbcUtilSingle= newJDBCUtilSingle();

}

}

}returnjdbcUtilSingle;

}privateJDBCUtilSingle() {

}//通过静态代码块注册数据库驱动,保证注册只执行一次

static{try{//注册驱动有如下方式://1.通过驱动管理器注册驱动,但会注册两次,并且会对类产生依赖。如果该类不存在那就报错了。//DriverManager.registerDriver(new com.mysql.jdbc.Driver());//2.与3类似//System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");

Class.forName("com.mysql.jdbc.Driver");//推荐使用方式

} catch(ClassNotFoundException e) {

e.printStackTrace();

}

}//获得连接

publicConnection getConnection() {try{

conn=DriverManager.getConnection(url,name,password);

}catch(SQLException e) {

e.printStackTrace();

}returnconn;

}//关闭连接

public voidcloseConnection(ResultSet rs, Statement statement, Connection con) {try{if (rs != null) {

rs.close();

}

}catch(SQLException e) {

e.printStackTrace();

}finally{try{if (statement != null) {

statement.close();

}

}catch(Exception e) {

e.printStackTrace();

}finally{try{if (con != null) {

con.close();

}

}catch(SQLException e) {

e.printStackTrace();

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值