码迷,mamicode.com
首页 > 数据库 > 详细

JDBC学习笔记(4):单例工具包

时间:2015-03-16 14:15:21      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

为了方便操作将连接数据库、关闭资源操作使用工具包完成:

 1 package com.xxyh.jdbc;
 2 import java.sql.Connection;
 3 import java.sql.DriverManager;
 4 import java.sql.SQLException;
 5 public class JdbcUtilsSingleton {
 6     private final String url = "jdbc:mysql://localhost:3306/jdbc";
 7     private final String user = "root";
 8     private final String password = "1234";
 9     
10     private static JdbcUtilsSingleton instance = null;
11     
12     private JdbcUtilsSingleton() {}
13     
14     static {
15         try {
16             Class.forName("com.mysql.jdbc.Driver");
17         } catch(ClassNotFoundException e) {
18             throw new ExceptionInInitializerError(e);
19         }
20     }
21     
22     /* 懒汉式 */
23     public static synchronized JdbcUtilsSingleton getInstance() {
24         if (instance == null) 
25             instance = new JdbcUtilsSingleton();
26         return instance;
27     }
28     
29     public Connection getConnection() throws SQLException {
30         return DriverManager.getConnection(url, user, password);
31     }
32 }

懒汉式的改进:

/* 懒汉式 */
    public static synchronized JdbcUtilsSingleton getInstance() {
        if (instance == null) 
            synchronized(JdbcUtilsSingleton.class) {
                if (instance == null)
                    instance = new JdbcUtilsSingleton();
            }
        return instance;
    }

测试工具包:

 1 package com.xxyh.jdbc.test;
 2 import java.sql.Connection;
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.sql.Statement;
 6 import com.xxyh.jdbc.JdbcUtils;
 7 import com.xxyh.jdbc.JdbcUtilsSingleton;
 8 public class JdbcUtilsSingletonTest {
 9     public static void main(String[] args) throws SQLException {
10         Connection conn = null;
11         Statement stmt = null;
12         ResultSet rs = null;
13         
14         try { 
15             conn = JdbcUtilsSingleton.getInstance().getConnection();
16             stmt = conn.createStatement();
17             rs = stmt.executeQuery("select * from user");
18             
19             while (rs.next()) {
20                 System.out.println(rs.getObject("id") + "\t" + rs.getObject("name") + "\t" +
21                         rs.getObject("birthday") + "\t" + rs.getObject("money"));
22             }
23         } finally {
24             JdbcUtils.close(rs, stmt, conn);
25         }
26     }
27 }
【测试结果】:
1    zhangs    1985-01-01    100.0
2    lisi      1986-01-01    200.0
3    wangwu    1987-01-01    300.0 

JDBC学习笔记(4):单例工具包

标签:

原文地址:http://www.cnblogs.com/xiaoxiaoyihan/p/4341563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!