jdbc是连接数据库必不可少的工具,但每次连接都要重新写一遍太麻烦了,也不利于代码的可读性,这里做一个工具类进行封装。
1 package com.gh; 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 /** 11 * 注意首先导驱动包。。。。。。。。。。。 12 * 13 * @author ganhang 14 * 15 */ 16 public class JdbcUtil { 17 // 驱动类 18 public static String Driver; 19 // 数据库地址 20 public static String url; 21 // 数据库用户名 22 public static String user; 23 // 数据库密码 24 public static String password; 25 // 用配置文件 改动只需重启 26 public static ResourceBundle rb = ResourceBundle.getBundle("com.gh.jdbc_config"); 27 static { 28 Driver = rb.getString("jdbc.Driver"); 29 url = rb.getString("jdbc.url"); 30 user = rb.getString("jdbc.user"); 31 password = rb.getString("jdbc.password"); 32 try { 33 Class.forName(Driver); 34 } catch (ClassNotFoundException e) { 35 e.printStackTrace(); 36 } 37 } 38 39 // 防止实例化 40 private JdbcUtil() {} 41 42 public static Connection getConnection() { 43 Connection conn = null; 44 try { 45 conn = DriverManager.getConnection(url, user, password); 46 } catch (SQLException e) { 47 e.printStackTrace(); 48 System.out.println("连接失败!"); 49 } 50 return conn; 51 } 52 53 public static void close(ResultSet rs, Statement s, Connection c) { 54 try { 55 if (rs != null) 56 rs.close(); 57 if (s != null) 58 s.close(); 59 if (c != null) 60 c.close(); 61 } catch (Exception e) { 62 e.printStackTrace(); 63 } 64 } 65 }
1 package com.gh; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 /** 8 * 测试 9 * @author ganhang 10 * 11 */ 12 public class test { 13 public static void main(String[] args) { 14 Connection conn=JdbcUtil.getConnection(); 15 String sql="select * from test"; 16 try { 17 PreparedStatement ps=conn.prepareStatement(sql); 18 ResultSet rs=ps.executeQuery(); 19 while(rs.next()){ 20 System.out.println(rs.getInt(1)); 21 } 22 JdbcUtil.close(rs, ps, conn); 23 } catch (SQLException e) { 24 e.printStackTrace(); 25 } 26 27 } 28 }
1 jdbc.Driver=oracle.jdbc.OracleDriver 2 jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl 3 jdbc.user=scott 4 jdbc.password=.