标签:loser object c jdb query rgs source str reac exception
PreparedStatement针对不同表的通用查询操作
public class PreparedStatementQueryTest {
@Test
public void testGetForList(){
String sql="select id,name,email from customers where id<?";
List<Customer> list = getForList(Customer.class, sql, 12);
list.forEach(System.out::println);
}
public<T> List<T> getForList(Class<T> clazz, String sql, Object ...args) {
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
//获取结果集的元数据
ResultSetMetaData rsmd = rs.getMetaData();
//通过ResultSetMetaData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
ArrayList<T> list = new ArrayList<>();
while (rs.next()) {
T t = clazz.newInstance();
for (int i = 0; i < columnCount; i++) {
//获取每个列的值
Object columnValue = rs.getObject(i + 1);
//获取每个列的别名
String columnName = rsmd.getColumnLabel(i + 1);
//给cust对象指定的columnName属性,赋值为columnValue
Field field = clazz.getDeclaredField(columnName);
field.setAccessible(true);
field.set(t, columnValue);
}
list.add(t);
}
return list;
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.closeResource(conn,ps,rs);
}
return null;
}
标签:loser object c jdb query rgs source str reac exception
原文地址:https://www.cnblogs.com/fate-/p/14922378.html