1 2 3 import java.io.FileInputStream; 4 import java.sql.*; 5 import java.util.Properties; 6 7 /** 8 * @author o_0sky 9 * @date 2019/2/19 0:10 10 */ 11 public class Jdbcutil { 12 static String driverName; 13 static String url; 14 static String user; 15 static String pwd; 16 17 //不論外面調用多少次getConnection方法,驅動都只要注冊一次 18 static { 19 try { 20 Properties p = new Properties(); 21 p.load(new FileInputStream("jdbc.properties")); 22 //給參數賦值 23 driverName = p.getProperty("driverName"); 24 url = p.getProperty("url"); 25 user = p.getProperty("user"); 26 pwd = p.getProperty("pwd"); 27 Class.forName(driverName); 28 } catch (Exception e) { 29 e.printStackTrace(); 30 } 31 } 32 //獲取連接 33 public static Connection getConnection() throws SQLException { 34 Connection con = DriverManager.getConnection(url,user,pwd); 35 return con; 36 } 37 //釋放資源 38 public static void release(Connection con, Statement statement, ResultSet resultSet){ 39 if (resultSet!=null){ 40 try { 41 resultSet.close(); 42 } catch (SQLException e) { 43 e.printStackTrace(); 44 } 45 } 46 if (statement!=null){ 47 try { 48 statement.close(); 49 } catch (SQLException e) { 50 e.printStackTrace(); 51 } 52 } 53 if (con!=null){ 54 try { 55 con.close(); 56 } catch (SQLException e) { 57 e.printStackTrace(); 58 } 59 } 60 } 61 }
測試類:
1 import java.sql.Connection; 2 import java.sql.ResultSet; 3 import java.sql.SQLException; 4 import java.sql.Statement; 5 6 /** 7 * @author o_0sky 8 * @date 2019/2/19 0:38 9 */ 10 public class Test { 11 public static void main(String[] args) throws SQLException { 12 //需要執行的Sql語句 13 String sql = "select * from tb_user"; 14 //通過工具類獲取連接 15 Connection con = Jdbcutil.getConnection(); 16 Statement statement = con.createStatement(); 17 //執行sql語句 18 ResultSet resultSet = statement.executeQuery(sql); 19 while (resultSet.next()) { 20 String name = resultSet.getString("name"); 21 String age = resultSet.getString("age"); 22 } 23 //釋放資源 24 Jdbcutil.release(con, statement, resultSet); 25 } 26 }