JDBCUtils 的通用代码

来源:互联网 发布:管家婆无法连接数据库 编辑:程序博客网 时间:2024/05/18 01:47

刚接触javaweb开发的人,要想和数据库打交道,都绕不开JDBCUtils的代码编写,下面分享一个比较好的代码风格的JDBCUtils类的编写。

public class JDBCUtils {
          private final static BasicDataSource ds;
          static{
         Properties pro=new Properties();
         try {
pro.load(JDBCUtils.class.getResourceAsStream("/dbcp2.properties"));
ds=BasicDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
          }
        
          public static Connection getConnection() throws SQLException{//得到连接
         return ds.getConnection();
          }
          public static void closeQuietly(AutoCloseable c){//安静地关闭资源,包括connection,statement,resultSet
         if(c!=null){
         try {
c.close();
} catch (Exception e) {

}
         }
          }
          
          public static void rollBack(Connection conn){//事务回滚
         if(conn!=null){
         try {
      conn.rollback();
       } catch (SQLException e) {
     
       }
         }
       
          }
          
          public static void closeAll(ResultSet rs){
         if(rs!=null){
         
        try {
        Statement stmt=rs.getStatement();
Connection conn=stmt.getConnection();
closeQuietly(rs);
closeQuietly(stmt);
closeQuietly(conn);
} catch (SQLException e) {
throw new RuntimeException(e);
}
         }
          }
          
          public static void closeStatementAndConnection(Statement stmt){
         if(stmt!=null){ 
        try {
Connection conn=stmt.getConnection();
closeQuietly(stmt);
closeQuietly(conn);
} catch (SQLException e) {
throw new RuntimeException(e);
}
         }
          }
          /**
           * 执行非查询代码
           * @param sql
           * @param params
           * @throws SQLException
           */
          public static void executeNonQuery(String sql, Object... params) throws SQLException{
         Connection conn=null; 
        try {
         conn=ds.getConnection();
executeNonQuery(conn, sql, params);
} finally{
closeQuietly(conn);
}
          }
          
          public static void executeNonQuery(Connection conn,String sql, Object... params) throws SQLException{
        PreparedStatement ps=null;  
         try {
ps=conn.prepareStatement(sql);
for(int i=0;i<params.length;i++){
ps.setObject(i+1, params[i]);
}
ps.execute();
} finally{
closeQuietly(ps);
}
          }
          
          public static ResultSet executeQuery(String sql,Object... params) throws SQLException{
         Connection conn=null;
         try{
         conn=ds.getConnection();
        return executeQuery(conn, sql, params);
         
         }catch(SQLException e){
         closeQuietly(conn);
         throw e;
         }
       
          }
          
          public static ResultSet executeQuery(Connection conn,String sql,Object... params) throws SQLException{
         PreparedStatement ps=null;
         try{
         ps=conn.prepareStatement(sql);
         for(int i=0;i<params.length;i++){
         ps.setObject(i+1, params[i]);
         }
         return  ps.executeQuery();
         
         }catch(SQLException e){
         closeQuietly(ps);
         throw e;
         }
       
          }
          
          /**
           * 得到最后插入的数据的id
           * @param sql
           * @param params
           * @return
           * @throws SQLException
           */
          public static long executeInsert(String sql,Object... params) throws SQLException{
         Connection conn=null;
           try {
  conn=ds.getConnection();
  return executeInsert(conn, sql, params);
  } finally{
  closeQuietly(conn);
  }
          }
          
          public static long executeInsert(Connection conn,String sql,Object... params) throws SQLException{
          PreparedStatement ps=null;
          PreparedStatement psForInsertId=null;
          ResultSet rs=null;
           try {
  ps=conn.prepareStatement(sql);
  for(int i=0;i<params.length;i++){
  ps.setObject(i+1, params[i]);
  }
  ps.execute();
  psForInsertId=conn.prepareStatement("select last_insert_id()");//需要使用同一个连接
  rs=psForInsertId.executeQuery();
  if(rs.next()){
  return rs.getLong(1);
  }else{
  throw new RuntimeException("没有找到id字段");
  }
  } finally{
  closeQuietly(ps);
  closeQuietly(rs);
  closeQuietly(psForInsertId);
  }
          }
          
          public static Object executeSingle(String sql,Object... params) throws SQLException{//适用于查询结果只有一行一列,比如说count(*)
         Connection conn=null;
        try{
         conn=ds.getConnection();
        return executeSingle(conn, sql, params);
         }
         finally{
         closeQuietly(conn);
         }
          }
          
          public static Object executeSingle(Connection conn,String sql,Object... params) throws SQLException{
         PreparedStatement ps=null;
         ResultSet rs=null;
         try{
         ps=conn.prepareStatement(sql);
         for(int i=0;i<params.length;i++){
         ps.setObject(i+1,params[i]);
         }
         rs= ps.executeQuery();
         if(rs.next()){
         return rs.getObject(1);
         }else{
         return null;
         }
         
         }
         finally{
        closeQuietly(rs);
        closeQuietly(ps);
         }
         }
          
         
}

代码当中我还使用了dbcp数据库连接池,从而提高系统的性能。数据库是mysql数据库。为了使代码能够正常运行需要引入3个jar包,jar包下载地址:http://download.csdn.net/detail/tonghangli/9859580

dbcp2.properties文件内容如下:(只要放在src下)

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名字?seUnicode=true&characterEncoding=UTF8
username=数据库账号
password=数据库密码


好了,本次的分享到此就结束了,赶快去happy地试一试吧

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 葡萄酒上面有一层白霉怎么办 手机一不小心把视频删了怎么办 柑橘7月份果实小怎么办 鹦鹉鱼身上有小白点怎么办 鹦鹉鱼身上烂了怎么办 红鹦鹉鱼变黑了怎么办 唱美声总夹嗓子怎么办 发财树树干出褶怎么办 月季花夏天换盆出现黄叶怎么办 刚种的月季枯了怎么办 新买的月季黄叶了怎么办 月季花叶孑轰发黄怎么办? 新种的月季苗弱怎么办? 月季换盆后浇透水叶子黄了怎么办 肉肉移栽后浇透水怎么办 月季花扦插的没长根发芽了怎么办 君子兰发的小苗怎么办 蔷薇光长枝条不开花怎么办 牡丹发芽又干了怎么办 擦皮炎平后皮肤变黑怎么办 误喝发霉的咖啡渣怎么办 狗吃了速溶咖啡怎么办 咖啡机放豆的地方进水怎么办 干吃咖啡粉上瘾怎么办 去良友花艺住宿怎么办 充气娃娃放了气怎么办 煮杜鹃根没有锅怎么办 淘宝店卖鲜花被买家拒收货怎么办 执业医师电子注册忘记密码怎么办 怀孕吃了油炸的怎么办 百合长得太高怎么办 百合的杆没了怎么办 百合花长得太细怎么办 沙漠玫瑰的花苞打不开怎么办 鲜切花 较小的花苞怎么办 大棚玫瑰苗水大涝的不长怎么办 鲜花买回来蔫了怎么办 喝玫瑰醋上火了怎么办 插在花泥上的花怎么办 插的花蔫了怎么办 紫睡莲的茎软了怎么办