标签:
为了方便操作将连接数据库、关闭资源操作使用工具包完成:
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 }
标签:
原文地址:http://www.cnblogs.com/xiaoxiaoyihan/p/4341563.html