PrepareStatement查询一条数据和多条数据
这里主要列出主要部分的代码:
查询一条数据
@Test
public void testGetInstance(){
String sql = "select id,name,email from customers where id=?";
Customer customer = getInstance(Customer.class,sql, 1);
System.out.println(customer);
String sql1 = "select id,name from stuinfo where id=?";
Stuinfo stuinfo = getInstance(Stuinfo.class,sql1,1);
System.out.println(stuinfo);
}
/**
* @author shan
* @date 2021/5/13
* 针对与不同表的查询操作,返回表中的一条记录
*/
public <T> T getInstance(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();
if (rs.next()) {
T t = clazz.newInstance();
//处理结果集一行数据中的每一列
for (int i = 0; i < columnCount; i++) {
//获取列值
Object columnValue = rs.getObject(i + 1);
//获取每个列的列名
String columnName = rsmd.getColumnName(i + 1);
//给cust对象指定columnName的属性,赋值为columnvalue,通过反射
Field field = clazz.getDeclaredField(columnName);
field.setAccessible(true);
field.set(t, columnValue);
}
return t;
}
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.closeResource(conn, ps, rs);
}
return null;
}
查询多条数据
@Test
public void testgetForList(){
String sql = "select id,name,email from customers where id<?";
List<Customer> list = getForList(Customer.class,sql, 5);
System.out.println(list);
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<T>();
while (rs.next()) {
T t = clazz.newInstance();
//处理结果集一行数据中的每一列
for (int i = 0; i < columnCount; i++) {
//获取列值
Object columnValue = rs.getObject(i + 1);
//获取每个列的列名
String columnName = rsmd.getColumnName(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;
}