`
ye_haiqiang
  • 浏览: 88098 次
  • 性别: Icon_minigender_1
  • 来自: 福州
社区版块
存档分类
最新评论

通用的增删改查

    博客分类:
  • JDBC
SQL 
阅读更多

CT-Manager项目终于告一段落了!这是我在开发时根据池老师的思想写出来的一个通用的增删改查,现在跟大家分享下!希望对大家有帮助!
package com.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBOperator
{
public static interface IRowMap
{
public void eachRow(ResultSet rs,int index) throws SQLException;
}
//通用的查询
public static int query(String sql,Object[] params,IRowMap rowprocess)
{
int count=0;
Connection conn=null;
DBConn dbConn=DBConn.getDBConn();
conn=dbConn.getConnection();
try
{
PreparedStatement ps=conn.prepareStatement(sql);
if(params!=null)
{
for(int i=0;i<params.length;i++)ps.setObject(i+1, params[i]);
}
ResultSet rs=ps.executeQuery();
while(rs.next()){
rowprocess.eachRow(rs, count);
count++;
}
DBConn.close(rs);
DBConn.close(ps);
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
DBConn.close(conn);
}
return count;
}
//通用的增删改
public static int execute(String sql,Object[] params){
int count=0;
Connection conn=null;
DBConn dbConn=DBConn.getDBConn();
conn=dbConn.getConnection();
try {
PreparedStatement ps=conn.prepareStatement(sql);
if(params!=null){
for(int i=0;i<params.length;i++){
int a=i+1;
ps.setObject(a, params[i]);
System.out.println("params["+a+"]="+params[i]);
}
}
System.out.println("sql="+sql);
count=ps.executeUpdate();
System.out.println("count="+count);
DBConn.close(ps);
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBConn.close(conn);
}

return count;

}
//执行查询
public ResultSet executeQuery(String sql){
ResultSet rs=null;
Statement st=null;
DBConn dbConn=DBConn.getDBConn();
Connection conn=null;
conn=dbConn.getConnection();
try {
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs=st.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Message="+e.getMessage());
}finally{
DBConn.close(st, rs, conn);
}
return rs;
}
//执行增、删、改
public int executeUpdate(String sql){
int count=0;
Connection conn=null;
ResultSet rs=null;
Statement st=null;
DBConn dbConn=DBConn.getDBConn();
conn=dbConn.getConnection();
try {
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
count=st.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBConn.close(st, rs, conn);
}
return count;
}
}
每天一点点点,希望对大家有帮助!

 

分享到:
评论
1 楼 xiaolng 2012-05-31  

相关推荐

Global site tag (gtag.js) - Google Analytics