專案中常用的增刪改方法和查詢方法
阿新 • • 發佈:2018-12-21
增刪改方法:
public static int update(String sql,Object...param) { int rowNumber=0; try { PreparedStatement psmt=DBConnection.getConnection().prepareStatement(sql); ParameterMetaData pmd=psmt.getParameterMetaData(); if(param!=null&¶m.length!=0¶m.length==pmd.getParameterCount()) { for(int i = 0,len=param.length;i<len;i++) { psmt.setObject(i+1, param[i]); } } DBUtils.printRealSql(sql, param); rowNumber=psmt.executeUpdate(); } catch (SQLException e) { log.error("update method error,this exception is:"+e.getMessage()); } finally { try { if(DBConnection.getConnection().getAutoCommit()) { DBConnection.closeConnection(DBConnection.getConnection()); } } catch (SQLException e) { e.printStackTrace(); } } return rowNumber; }
查詢方法:
public static<T> T query(String sql,ResultSetHandler<T> rsh,Object...param){ T t=null; try { PreparedStatement psmt=DBConnection.getConnection().prepareStatement(sql); ParameterMetaData pmd=psmt.getParameterMetaData(); if(param!=null&¶m.length!=0&¶m.length==pmd.getParameterCount()) { for(int i = 0,len=param.length;i<len;i++) { psmt.setObject(i+1, param[i]); } } ResultSet rs=psmt.executeQuery(); t= rsh.handler(rs); } catch (SQLException e) { log.error("query method error,the exception is:"+e.getMessage()); } finally { try { if(DBConnection.getConnection().getAutoCommit()) { DBConnection.closeConnection(DBConnection.getConnection()); } } catch (SQLException e) { e.printStackTrace(); } } return t; }