使用DBUtils对数据库进行操作时,可将该表中属性封装为一个类,然后用可变数组List接收该类型数据,在关闭conn后还使用该结果集。
原代码如下:
public class JDBC_DBUtils {
class Brand{
int id;
String brand_name;
String company_name;
int ordered;
String description;
int status;
}
//使用apche-DBUtils工具类+druid完成对表的crud操作
@Test
public void testQueryMany() throws SQLException {
Connection connection = JDBCUtilsByDruid.getConnection();
// 使用DBUtils的类与接口:QueryRunner
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from tb_brand where status = ?";
List<Brand> list = queryRunner.query(connection, sql, new BeanListHandler<>(Brand.class), 1);
System.out.println("输出集合信息:");
for (Brand brand : list){
System.out.println(brand);
}
//断开连接
JDBCUtilsByDruid.close(null, null, connection);
}
}
但在运行时出现错误:
java.sql.SQLException: Cannot create JDBC.src.JDBC_DBUtils$Brand: JDBC.src.JDBC_DBUtils$Brand Query: select * from tb_brand where status = ? Parameters: [1]
解决办法为:将内部类声明为static,并在使用时通过外部类.内部类来引用;
public class JDBC_DBUtils {
public static class Brand{
int id;
String brand_name;
String company_name;
int ordered;
String description;
int status;
}
//使用apche-DBUtils工具类+druid完成对表的crud操作
@Test
public void testQueryMany() throws SQLException {
Connection connection = JDBCUtilsByDruid.getConnection();
// 使用DBUtils的类与接口:QueryRunner
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from tb_brand where status = ?";
List<JDBC_DBUtils.Brand> list = queryRunner.query(connection, sql, new BeanListHandler<>(JDBC_DBUtils.Brand.class), 1);
System.out.println("输出集合信息:");
for (JDBC_DBUtils.Brand brand : list){
System.out.println(brand);
}
//断开连接
JDBCUtilsByDruid.close(null, null, connection);
}
}
或者创建一个独立的类文件存放Brand类,问题解决。
public class Brand {
int id;
String brand_name;
String company_name;
int ordered;
String description;
int status;
}
-------------------------------------------------------------
若查询出来结果为null,在类中对属性加入Getter和Setter方法即可。