sql代码:SELECT * FROM表WHERE列

问题描述 投票:-3回答:2

我有一个表名“Coupon”,我在eclipse上使用java。

我有一个方法getCoupon(long id);这给了我id的优惠券,我这样写:

public Coupon getCoupon(long id) {
        Connection con = ConnectionPool.getInstance().getConnection();
        String sql = "SELECT * FROM Coupon WHERE TYPE=?";
        Coupon coupon = new Coupon();
        try (PreparedStatement pstmt = con.prepareStatement(sql);){
            pstmt.setLong(1, id);
            try (ResultSet rs = pstmt.executeQuery();) {
                if (rs.next()) {
                    coupon.setId(rs.getLong(1));
                    coupon.setTitle(rs.getString(2));
                    coupon.setStartDate(rs.getDate(3));
                    coupon.setEndDate(rs.getDate(4));
                    coupon.setAmount(rs.getInt(5));
                    coupon.setType(CouponType.valueOf(rs.getString(6)));
                    coupon.setMessage(rs.getString(7));
                    coupon.setPrice(rs.getDouble(8));
                    coupon.setImage(rs.getString(9));
                } else {
                    System.out.println("Coupon ID: " + id + " could not be found\n");
                }
            }
        } catch (SQLException e) {
            CouponSystemException ex = new CouponSystemException("Coupon ID: " + id + " could not be retrieved\n", e);
            System.out.println(ex.getMessage());
            System.out.println(e);
        }
        ConnectionPool.getInstance().returnConnection(con);
        return coupon;
    }

我想制作另一种方法,它通过它的类型给我优惠券!但TYPE COLUMN不在第一列,它给了我例外。有什么建议?

java sql jdbc
2个回答
0
投票

您可以尝试按名称而不是序号位置引用列:

rs.getLong("type")

而不是:

rs.getLong(1)

有时,表会以更改列顺序的方式重新创建表,因此依赖列的序号位置会失败。

作为进一步的防御,我总是列出我想要的列,而不是编码;

select * ...

这也更有效,因为您的Java程序不会回退所有列,只会回收它所需的列。


0
投票

第一:看起来你的代码中有问题如下

String sql = "SELECT * FROM Coupon WHERE TYPE=?";

我认为TYPE=?应该被理解为ID=?

第二:我看到TYPE列是字符串(因为coupon.setType(CouponType.valueOf(rs.getString(6)));)所以你必须将pstmt.setLong(1, id);更改为pstmt.setString(1, couponType.getValue());

第三:始终避免使用SELECT *而是键入所需的所有列。

第四:尝试概括两种方法getCouponByID(long id)getCouponByType(CouponType couponType),以便将来的维护更容易。

第五:把ConnectionPool.getInstance().returnConnection(con);放在finally条款中,这样你一定会回到连接池。

第六:使用PreparedStatement的性能较低,如果你使用它少于很多次(即100次),你只使用它一次。在这种情况下使用Statement具有更好的性能,但如果插入用户类型String,请注意SQL注入。在这种情况下,不要担心因为它是long类型。

© www.soinside.com 2019 - 2024. All rights reserved.