选择查询显示错误结果

时间:2017-12-26 21:56:06

标签: java mysql

我想检查数据库表中是否有数据可用。如果没有,它会插入数据。但在第一个按钮点击它完美。当我尝试再次单击该按钮并使用相同的值时,它会插入到表中。请帮助别人

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:

    try {
        // TODO add your handling code here:
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        ArrayList<String> list = new ArrayList<>();
        Object obj[] = null;
        Class.forName("com.mysql.jdbc.Driver");
        java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cem?useSSL=false", "root", "123");
        //here stu is database name, root is username and password
        Statement stmt = con.createStatement();

        String pn = "select gname from games where gname='" + jTextField1.getText() + "'";
        ResultSet rsPn = stmt.executeQuery(pn);
        System.out.println(rsPn.next());
        if (rsPn.next() == false) {

            String q = ("insert into games(gid,gname) values(NULL,'" + jTextField1.getText() + "')");
            int i = 0;
            i = stmt.executeUpdate(q);
            if (i > 0) {
                System.out.println("success");
                list.add(jTextField1.getText());
                obj = list.toArray();
                model.addRow(obj);

            } else {
                System.out.println("stuck somewhere");

            }

            StudentDetails.details();
            jTextField1.setForeground(Color.BLACK);
            stmt.close();
            con.close();
        } else {
            jTextField1.setForeground(Color.red);
            System.out.println("Name Already exist");
        }

    } catch (SQLException ex) {
        Logger.getLogger(InsertPanel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(InsertPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
}                

1 个答案:

答案 0 :(得分:4)

您两次致电next()

System.out.println(rsPn.next());
if (rsPn.next() == false) {

第二个调用将返回false,即使已经存在一行(尽管一旦有两行或更多行,它应该有效)。改为使用变量:

boolean hasNext = rdPn.next();
System.out.println(hasNext);
if (!hasNext) {