解决java.sql.SQLException: Cannot create JDBC.src.JDBC_DBUtils$Brand

        使用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方法即可。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值