0
点赞
收藏
分享

微信扫一扫

使用PrepareStatement实现针对于不同表的查询操作涉及到泛型和反射技术(返回的结果集还是一行多列)


使用PrepareStatement实现针对于不同表的查询操作涉及到泛型和反射技术(返回的结果集还是一行多列)

返回的结果是一条记录

使用PrepareStatement实现针对于不同表的查询操作涉及到泛型和反射技术(返回的结果集还是一行多列)_sql

public static <T>  T queryTablesCommon(Class<T> clazz,String sql,Object... args){
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
connection = JDBCUtils.getConnection();
ps = connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
if(rs.next()){
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
T t = clazz.newInstance();
for(int i=0;i<columnCount;i++){
String columnLabel = rsmd.getColumnLabel(i + 1);
Object objectValue = rs.getObject(i + 1);
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t,objectValue);
}
return t;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(connection,ps,rs);
}
return null;
}

@Test
public void testTablesCommonQuery(){
String sql="select name,email from customer where id=?";
Customer customer = Common.queryTablesCommon(Customer.class, sql, 1);
System.out.println(customer);

String sql1="select order_id orderId,order_name orderName from `order` where order_id=?";
Order order = Common.queryTablesCommon(Order.class, sql1, 1);
System.out.println(order);
}

使用PrepareStatement实现针对于不同表的查询操作涉及到泛型和反射技术(返回的结果集还是一行多列)_mysql_02


使用PrepareStatement实现针对于不同表的查询操作涉及到泛型和反射技术(返回的结果集还是一行多列)_mysql_03


使用PrepareStatement实现针对于不同表的查询操作涉及到泛型和反射技术(返回的结果集还是一行多列)_数据库_04


举报

相关推荐

0 条评论