JDBC的crud通用方法

package com.platform_db.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.platform_db.dao.IObjectDao;
import com.platform_db.db.DBUtil;

public class ObjectDaoImpl implements IObjectDao{
public List<?> find(String sql,Object[] pars) throws Exception {
PreparedStatement ps = null;
ResultSet rs = null;

Connection conn = DBUtil.openConnection();
ps = conn.prepareStatement(sql);
for (int i = 0;i < pars.length ; i++) {
ps.setObject(i+1, pars[i]);
}
rs = ps.executeQuery();

List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
while( rs.next() ){
Map<String , Object> map = new HashMap<String , Object>();
for (int i = 1; i <= columnCount; i++) {
map.put(md.getColumnName(i), rs.getObject(i));
}
data.add(map);
}

rs.close();
ps.close();
conn.close();

return data;
}

public boolean exec(String sql, Object[] pars) throws Exception {
Connection conn = DBUtil.openConnection();
conn.setAutoCommit(false);

PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0;i < pars.length ; i++) {
ps.setObject(i+1, pars[i]);
}
boolean flag = ps.execute();

conn.commit();
conn.setAutoCommit(true);
ps.close();
conn.close();
return flag;
}

public int[] execBatch(String sql, List<Object[]> list) throws Exception {
Connection conn = DBUtil.openConnection();
conn.setAutoCommit(false);

PreparedStatement ps = conn.prepareStatement(sql);
for(Object[] pars : list){
for (int i = 0;i < pars.length ; i++) {
ps.setObject(i+1, pars[i]);
}
ps.addBatch();
}

int[] counts = ps.executeBatch();

conn.commit();
conn.setAutoCommit(true);
ps.close();
conn.close();

return counts;
}
}

posted @ 2015-08-05 20:12  [3]  阅读(233)  评论(0编辑  收藏  举报