标签:连接 span resultset web 注册 输入流 static class cat
第一种(单纯提取注册驱动和获取连接):
把注册驱动,获取连接一起写入工具类静态方法里,并释放资源
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.PreparedStatement; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 7 /** 8 * 提供获取连接和释放资源的方法 9 * 10 * @author Administrator 11 * 12 */ 13 public class JDBCUtils_V1 { 14 /** 15 * 获取连接 16 * 17 * @return 18 */ 19 public static Connection getConnection() { 20 Connection conn = null; 21 try { 22 Class.forName("com.mysql.jdbc.Driver"); 23 conn = DriverManager.getConnection("jdbc:mysql://192.168.1.32:3306/web09", "root", "qweasd"); 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } 27 return conn; 28 } 29 /** 30 * 释放资源 31 * @param conn 32 * @param pstmt 33 * @param rs 34 */ 35 public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) { 36 if (rs != null) { 37 try { 38 rs.close(); 39 } catch (SQLException e) { 40 e.printStackTrace(); 41 } 42 } 43 if (pstmt != null) { 44 try { 45 pstmt.close(); 46 } catch (SQLException e) { 47 e.printStackTrace(); 48 } 49 } 50 if (conn != null) { 51 try { 52 conn.close(); 53 } catch (SQLException e) { 54 e.printStackTrace(); 55 } 56 } 57 } 58 }
第二种(调用properties文件)
把调用过程写入静态代码块中
1 private static String driver; 2 private static String url; 3 private static String username; 4 private static String password; 5 static { 6 ResourceBundle rb = ResourceBundle.getBundle("a"); 7 driver = rb.getString(driver); 8 url = rb.getString(url); 9 username = rb.getString(username); 10 password = rb.getString(password); 11 }
第三种(通过类加载器):
1 static { 2 try { 3 // 1.通过当前类获取类加载器 4 ClassLoader cl = JDBCUtils_V3.class.getClassLoader(); 5 // 2.通过类加载器获取输入流 6 InputStream is = cl.getResourceAsStream("a.properties"); 7 // 3.创建一个properties对象 8 Properties pp = new Properties(); 9 // 4.加载输入流 10 pp.load(is); 11 // 5.获取相关参数 12 driver = pp.getProperty(driver); 13 url = pp.getProperty(url); 14 username = pp.getProperty(username); 15 password = pp.getProperty(password); 16 } catch (IOException e) { 17 e.printStackTrace(); 18 } 19 }
标签:连接 span resultset web 注册 输入流 static class cat
原文地址:http://www.cnblogs.com/VDblog/p/7497225.html