new ScalarHandler()-->返回值为long,不能用int接收!!!

时间:2022-07-28
本文章向大家介绍new ScalarHandler()-->返回值为long,不能用int接收!!!,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.用int接收,错误如下:

public class ProductDaoImpl implements ProductDao {
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
    //根据tid返回每个种类的总数
    @Override
    public int findCountProduct(int tid) throws SQLException {
        String sql = "select count(1) from product where t_id = ?";
        int i = (int)qr.query(sql, new ScalarHandler(), tid);
        return i;
    }
}

2.按照错误提示:new ScalarHandler()需要使用long接收。修改后如下:

public class MyTest {
    public static void main(String[] args) throws Exception {
        ProductDao productDao = new ProductDaoImpl();
        System.out.println(productDao.findCountProduct(1));
    }
}

3.错误原因:

qr.query()返回object类型 ,先转成 ScalarHandler的Long类型 然后 在转为 int类型,之前我直接就转成int类型所以就GG了呱~。