jdbc连接数据库(单例模式)


01 package com.sli;
02
03 import java.sql.Connection;
04 import java.sql.DriverManager;
05 import java.sql.ResultSet;
06 import java.sql.SQLException;
07 import java.sql.Statement;
08
09 /**
10 *
11 * @author 罗盛力 JDBC辅助类 用于构建数据库连接(采用单例模式)
12 */
13 public final class JDBCUtilSingle {
14 // 该url为缺省方式(省略主机跟端口)
15 // 完整为:jdbc:mysql//localhost:3306/test
16 static String url = "jdbc:mysql:///test";
17 static String name = "root";
18 static String password = "sli";
19 static Connection conn = null;
20 private static JDBCUtilSingle jdbcUtilSingle = null;
21
22 public static JDBCUtilSingle getInitJDBCUtil() {
23 if (jdbcUtilSingle == null) {
24 // 给类加锁 防止线程并发
25 synchronized (JDBCUtilSingle.class) {
26 if (jdbcUtilSingle == null) {
27 jdbcUtilSingle = new JDBCUtilSingle();
28 }
29 }
30 }
31 return jdbcUtilSingle;
32 }
33
34 private JDBCUtilSingle() {
35 }
36
37 // 通过静态代码块注册数据库驱动,保证注册只执行一次
38 static {
39 try {
40 // 注册驱动有如下方式:
41 // 1.通过驱动管理器注册驱动,但会注册两次,并且会对类产生依赖。如果该类不存在那就报错了。
42 // DriverManager.registerDriver(new com.mysql.jdbc.Driver());
43 // 2.与3类似
44 // System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");
45 Class.forName("com.mysql.jdbc.Driver");// 推荐使用方式
46 } catch (ClassNotFoundException e) {
47 e.printStackTrace();
48 }
49 }
50
51 // 获得连接
52 public Connection getConnection() {
53 try {
54 conn = DriverManager.getConnection(url,name,password);
55 } catch (SQLException e) {
56 e.printStackTrace();
57 }
58 return conn;
59
60 }
61
62 // 关闭连接
63 public void closeConnection(ResultSet rs, Statement statement, Connection con) {
64 try {
65 if (rs != null) {
66 rs.close();
67 }
68 } catch (SQLException e) {
69 e.printStackTrace();
70 } finally {
71 try {
72 if (statement != null) {
73 statement.close();
74 }
75 } catch (Exception e) {
76 e.printStackTrace();
77 } finally {
78 try {
79 if (con != null) {
80 con.close();
81 }
82 } catch (SQLException e) {
83 e.printStackTrace();
84 }
85 }
86 }
87 }
88
89 }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值