Java通用oracle數據庫連接
阿新 • • 發佈:2017-09-28
tco str nag jdbc 用戶名 數組 catch for source
Java中oracle數據庫連接寫一個通用類UBUtil(){}
import java.io.InputStream; import java.sql.*; import java.util.Properties; public class DBUtil { private static Connection con; private static String url; private static String user; private static String pwd; public DBUtil() { }static { try { Class.forName("oracle.jdbc.driver.OracleDriver"); InputStream is = DBUtil.class.getResourceAsStream("/db.properties");//db.properties 是一個用戶配置文件傳用戶名密碼 Properties prop=new Properties(); prop.load(is); url=prop.getProperty("url"); user=prop.getProperty("user"); pwd=prop.getProperty("password"); con = DriverManager.getConnection(url, user, pwd); }catch (Exception e){ } } public static ResultSet find(String sql){ con=getCon(); try { Statement smt=con.createStatement(); ResultSet rs=smt.executeQuery(sql); return rs; } catch (SQLException e) { e.printStackTrace(); return null; } } public static ResultSet find(String sql,Object ...pram){//...pram數組 con=getCon(); try { PreparedStatement smt=con.prepareStatement(sql); for (int i=0;i<pram.length;i++){ smt.setObject(i+1,pram[i]); } ResultSet rs=smt.executeQuery(); return rs; } catch (SQLException e) { e.printStackTrace(); return null; } } public static void insert(String sql,Object ...pram){//...pram數組 con=getCon(); try { PreparedStatement smt=con.prepareStatement(sql); for (int i=0;i<pram.length;i++){ smt.setObject(i+1,pram[i]); } smt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public static Connection getCon(){ try { if(con==null||con.isClosed()) con = DriverManager.getConnection(url, user, pwd); } catch (SQLException e) { e.printStackTrace(); } return con; } }
Java通用oracle數據庫連接