JDBCUtil
1 package com.itheima.uitl; 2 3 import java.io.FileInputStream; 4 import java.io.InputStream; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.ResultSet; 8 import java.sql.SQLException; 9 import java.sql.Statement; 10 import java.util.Properties; 11 12 public class JDBCUtil { 13 14 static String driverClass = null; 15 static String url = null; 16 static String name = null; 17 static String password= null; 18 19 static{ 20 try { 21 //1. 创建一个属性配置对象 22 Properties properties = new Properties(); 23 InputStream is = new FileInputStream("jdbc.properties"); 24 25 //使用类加载器,去读取src底下的资源文件。 后面在servlet 26 // InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); 27 //导入输入流。 28 properties.load(is); 29 30 //读取属性 31 driverClass = properties.getProperty("driverClass"); 32 url = properties.getProperty("url"); 33 name = properties.getProperty("name"); 34 password = properties.getProperty("password"); 35 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } 39 } 40 41 /** 42 * 获取连接对象 43 * @return 44 */ 45 public static Connection getConn(){ 46 Connection conn = null; 47 try { 48 Class.forName(driverClass); 49 //静态代码块 ---> 类加载了,就执行。 java.sql.DriverManager.registerDriver(new Driver()); 50 //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 51 //DriverManager.getConnection("jdbc:mysql://localhost/test?user=monty&password=greatsqldb"); 52 //2. 建立连接 参数一: 协议 + 访问的数据库 , 参数二: 用户名 , 参数三: 密码。 53 conn = DriverManager.getConnection(url, name, password); 54 } catch (Exception e) { 55 e.printStackTrace(); 56 } 57 return conn; 58 } 59 60 /** 61 * 释放资源 62 * @param conn 63 * @param st 64 * @param rs 65 */ 66 public static void release(Connection conn , Statement st , ResultSet rs){ 67 closeRs(rs); 68 closeSt(st); 69 closeConn(conn); 70 } 71 public static void release(Connection conn , Statement st){ 72 closeSt(st); 73 closeConn(conn); 74 } 75 76 77 private static void closeRs(ResultSet rs){ 78 try { 79 if(rs != null){ 80 rs.close(); 81 } 82 } catch (SQLException e) { 83 e.printStackTrace(); 84 }finally{ 85 rs = null; 86 } 87 } 88 89 private static void closeSt(Statement st){ 90 try { 91 if(st != null){ 92 st.close(); 93 } 94 } catch (SQLException e) { 95 e.printStackTrace(); 96 }finally{ 97 st = null; 98 } 99 } 100 101 private static void closeConn(Connection conn){ 102 try { 103 if(conn != null){ 104 conn.close(); 105 } 106 } catch (SQLException e) { 107 e.printStackTrace(); 108 }finally{ 109 conn = null; 110 } 111 } 112 }