首页 > 解决方案 > 获取“将 nvarchar 值转换为 JDBC 数据类型 DOUBLE 时发生错误。”

问题描述

我正在尝试运行 getAllCoupons() 方法,该方法读取优惠券表并将其发送回 Angular 服务,但我收到此消息将 nvarchar 值转换为 JDBC 数据类型 DOUBLE 时发生错误。我没有看到任何错误的字段。

我最初认为日期是问题,所以我发表了评论,但我仍然遇到问题

我的 DBDAO 代码:

public ArrayList<Coupon> getAllCoupon() throws CouponException {
        ArrayList<Coupon> coupons = new ArrayList<>();
        Connection con = pool.getConnection();


        try {
            PreparedStatement st = con.prepareStatement("select * from coupons");

            ResultSet rs = st.executeQuery();
            while (rs.next()) {
                long id = rs.getLong(1);
                String title = rs.getString(2);
                String message = rs.getString(3);
                String image = rs.getString(4);
            //  Date startDate = rs.getDate(5);
            //  Date endDate = rs.getDate(6);
                int amount = rs.getInt(5);
                double price = rs.getDouble(6);
                Coupontypes type = Coupontypes.valueOf(rs.getString(7));
                coupons.add(new Coupon(id, title, message, image, amount, price, type));

            }

            return coupons;

        } catch (SQLException e) {
            throw new CouponException(e.getMessage());

        } finally {
            pool.returnConnection(con);
        }
        }

我的桌子:

CouponID bigint
Title nvarchar(50)
StartDate date
EndDate date
Amount int Type nvarchar(50)
Message nvarchar(MAX)
Price float Unchecked Image nvarchar(50)

我希望得到一个优惠券对象,这样我就可以用 *ngFor 在有角度的网站上显示它

标签: javasqljdbc

解决方案


您试图java.lang.String投射到java.lang.Double. 如果您将 double 作为字符串存储,那么您可以执行double price = new Double(rs.getString(6)). 确保您的列不会为空,并且它将始终返回双精度值以避免异常。


推荐阅读