标签:
JDBC获取数据库连接的帮助类
1 import java.io.InputStream; 2 import java.sql.Connection; 3 import java.sql.DriverManager; 4 import java.sql.ResultSet; 5 import java.sql.Statement; 6 import java.util.Properties; 7 8 public class jdbcUtil { 9 10 private static String driver; 11 private static String url; 12 private static String id; 13 private static String password; 14 15 //加载文件,获取配置参数 16 static{ 17 Properties prop=new Properties(); 18 InputStream is; 19 try { 20 is = jdbcUtil.class.getClassLoader() 21 .getResourceAsStream("com/sy/db/db.properties"); 22 prop.load(is); 23 driver = prop.getProperty("driver"); 24 url = prop.getProperty("url"); 25 id = prop.getProperty("id"); 26 password = prop.getProperty("password"); 27 } catch (Exception e1) { 28 e1.printStackTrace(); 29 } 30 } 31 32 //注册驱动 33 static{ 34 try { 35 Class.forName(driver); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } 39 } 40 41 //取得连接 42 public static Connection getMysqlConnection(){ 43 Connection conn=null; 44 try { 45 conn=DriverManager.getConnection(url,id,password); 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } 49 return conn; 50 } 51 52 //关闭流 53 public static void close(ResultSet rs){ 54 if(null!=rs){ 55 try { 56 rs.close(); 57 } catch (Exception e) { 58 e.printStackTrace(); 59 } 60 } 61 } 62 public static void close(Statement state){ 63 if(null!=state){ 64 try { 65 state.close(); 66 } catch (Exception e) { 67 e.printStackTrace(); 68 } 69 } 70 } 71 public static void close(Connection conn){ 72 if(null!=conn){ 73 try { 74 conn.close(); 75 } catch (Exception e) { 76 e.printStackTrace(); 77 } 78 } 79 } 80 }
标签:
原文地址:http://www.cnblogs.com/sweetyu/p/4942079.html