发布网友 发布时间:2022-04-23 11:30
共3个回答
懂视网 时间:2022-04-30 11:46
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;
}
}
JDBC的crud通用方法
标签:
热心网友 时间:2022-04-30 08:54
public static Object get(Class clazz,String sql,Object[] pars)热心网友 时间:2022-04-30 10:12
Connection conn = getConnection();