apache-DBUtis 工具类 + druid 完成对表的crud *** 作报错

apache-DBUtis 工具类 + druid 完成对表的crud *** 作报错,第1张

场景:

apache-DBUtis 工具类 + druid 完成对表的crud *** 作

public void testQueryMany() throws SQLException {
        Connection connection = JDBCUtilsByDruid.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        String sql = "select * from actor where id >= ?";
        List<Actor> list = queryRunner.query(connection, sql, new BeanListHandler<>(Actor.class), 1);
        for (Actor actor : list) {
            System.out.println(actor);
        }
        JDBCUtilsByDruid.close(null,null,connection);
    }
报错

分析原因

select * from actor where id >= 1放到数据库中运行正常

String sql = "select * from actor where id >= ?";
替换为 String sql = "select id, name from actor where id >= ?";
运行成功

直到添加到borndate又开始报错
String sql = "select id,name,sex,phone,borndate from actor where id >= ?";
确定了是数据库字段borndate的问题
borndate是datetime类型,而actor类的borndate是Date类型
但是用土方法去封装也能成功

public void testSelectToArrayList() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet set = null;
        String sql = "select * from actor where id >= ?";
        ArrayList<Actor> list = new ArrayList<>();
        try {
            connection = JDBCUtilsByDruid.getConnection();
            System.out.println(connection.getClass());
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,1);
            set = preparedStatement.executeQuery();
            while (set.next()) {
                int id = set.getInt("id");
                String name = set.getString("name");
                String sex = set.getString("sex");
                Date borndate = set.getDate("borndate");
                String phone = set.getString("phone");
                list.add(new Actor(id,name,sex,borndate,phone));
            }
            System.out.println(list);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtilsByDruid.close(set, preparedStatement, connection);
        }
    }


最后把数据库borndate的类型由datetime改为date

alter table actor
    modify  column borndate datetime;

成功运行

总结:使用apache-DBUtis 工具类 字段的Date类型必须和数据库字段的date对应

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/724567.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存