验证该行是否在mySQL表中不可用

时间:2016-05-09 15:59:03

标签: java mysql

如果数据库中没有行,我想要消息(库存中没有该行)。我尝试以下代码,但错误....!

//代码

try {

            Connection con = Database.mySqlCon();
            String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
            PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();

            int count = 0;
            while (rs.next()){
                count = count + 1;
            }

            if (count == 1) {

                JOptionPane.showMessageDialog(null, "Item is available in Stock"
            } else {
                JOptionPane.showMessageDialog(null, "ID:" + txtS.getText() + "is not available in the Stock please update the Stock");

            }
        } catch (Exception e) {

            JOptionPane.showMessageDialog(null, e);
            e.printStackTrace();
}

//错误....

java.sql.SQLException: No value specified for parameter 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)

..... ..... .... ....  请帮忙.....

2 个答案:

答案 0 :(得分:1)

您没有为此设置值?在display: block声明中。

鉴于它是一个ID我会认为它是一个int。

你需要:

SELECT

修改

尝试将您的方法更改为:

Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, value);

ResultSet rs = ps.executeQuery();

答案 1 :(得分:0)

感谢@Matt提供帮助

我使用这段代码得到了一个完美的答案......

尝试{

            Connection con = Database.mySqlCon();
            String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, txtS.getText());
            ResultSet rs = ps.executeQuery();



            int count = 0;
            while (rs.next()){

                // code update here

                count = rs.getInt(1);
              //  count = count + 1;
            }

            if (count == 1) {