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	}


猜你喜欢

转载自hechuanzhen.iteye.com/blog/1635887