`

DBUtil

 
阅读更多

package util;

import java.sql.*;

public class DBUtil {
 
 public static Connection getConn() throws Exception{
  try{
   Class.forName("oracle.jdbc.driver.OracleDriver");
   return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:mydb", "MyUser", "mydb");
  }catch(Exception e){
   throw new Exception("获取数据库连接失败!");
  }
 }
 
 public static void closeConn(Connection conn) throws Exception{
  try{
   if(null != conn && !conn.isClosed()){
    conn.close();
   }
  }catch(Exception e){
   throw new Exception("关闭数据库连接失败!");
  }
 }
 
 private static void setParam(Object[] paramObj, PreparedStatement ps) throws Exception{
  try{
   if(null !=paramObj && paramObj.length > 0){
    for(int i = 1; i <= paramObj.length; i++){
     ps.setObject(i, paramObj[i-1]);
    }
   }
  }catch(Exception e){
   throw new Exception("给PreparedStatement设置失败!");
  }
 }
 
 public static ResultSet query(String sql, Object[] paramObj, Connection conn) throws Exception{
  PreparedStatement ps = conn.prepareStatement(sql);
  setParam(paramObj, ps);
  return ps.executeQuery();
 }
 
 public static void update(String sql, Object[] paramObj, Connection conn) throws Exception{
  PreparedStatement ps = conn.prepareStatement(sql);
  setParam(paramObj, ps);
  ps.executeUpdate();
 }
 
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics