1 package util; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 import java.util.ResourceBundle; 9 10 public class JdbcUtils { 11 12 static final String DRIVERCLASS ; 13 static final String URL ; 14 static final String USER ; 15 static final String PASSWORD ; 16 17 static{ 18 19 //獲取ResourceBundle 20 /* 21 * jdbc 為 src 下的 jdbc.properties 22 * */ 23 ResourceBundle bundle = ResourceBundle.getBundle("jdbc"); 24 25 //獲取指定元素 26 DRIVERCLASS = bundle.getString("driverClass"); 27 URL = bundle.getString("url"); 28 USER = bundle.getString("user"); 29 PASSWORD = bundle.getString("password"); 30 } 31 32 static{ 33 try { 34 //注冊驅動 35 Class.forName(DRIVERCLASS); 36 } catch (ClassNotFoundException e) { 37 e.printStackTrace(); 38 } 39 } 40 41 //獲取連接 42 public static Connection getConnection() throws SQLException{ 43 return DriverManager.getConnection(URL, USER, PASSWORD); 44 } 45 46 /** 47 * 釋放資源 48 * @param conn 49 * @param st 50 * @param rs 51 */ 52 public static void CloseResource(Connection conn,Statement st , ResultSet rs){ 53 closeResultSet(rs); 54 closeStaement(st); 55 closeConn(conn); 56 } 57 58 /** 59 *釋放連接 60 * @param conn 61 * 連接 62 */ 63 public static void closeConn(Connection conn){ 64 if(conn!=null){ 65 try { 66 conn.close(); 67 } catch (SQLException e) { 68 e.printStackTrace(); 69 }finally{ 70 conn = null ; 71 } 72 } 73 } 74 75 /** 76 * 釋放語句執行者 77 * @param st 78 * 語句執行者 79 */ 80 public static void closeStaement(Statement st){ 81 if(st!=null){ 82 try { 83 st.close(); 84 } catch (SQLException e) { 85 e.printStackTrace(); 86 }finally{ 87 st = null ; 88 } 89 } 90 } 91 92 /** 93 * 釋放結果集 94 * @param rs 95 * 結果集 96 */ 97 public static void closeResultSet(ResultSet rs){ 98 if(rs!=null){ 99 try { 100 rs.close(); 101 } catch (SQLException e) { 102 e.printStackTrace(); 103 }finally{ 104 rs = null ; 105 } 106 } 107 } 108 109 }
1 driverClass=com.mysql.jdbc.Driver 2 url=jdbc:mysql://localhost:3306/數據庫名 3 user=用戶名 4 password=密碼