我无法将Java连接到MySQL

时间:2014-04-18 02:18:49

标签: java mysql jdbc

我必须连接到MySQL中相同数据库的类,我连接的第一个类是可以的,但连接到同一个表的第二个类显示如下错误消息

  

无法使用executeQuery()发布数据操作语句。

怎么了? 这是第一个没有错误的类代码:

    if(evt.getKeyChar()==KeyEvent.VK_ENTER ){
            try {
    rs = stmt.executeQuery("select * from TbSignUp where username='"+txt1.getText()+"' and userpassword='"+txt2.getText()+"'");
            if(rs.next()){
            FrmMain fm = new FrmMain();
            JOptionPane.showMessageDialog(null, "Welcome to "+txt1.getText()+"","Information Message",JOptionPane.INFORMATION_MESSAGE);
            fm.setVisible(true);
            this.setVisible(false);
            }
            else{
            JOptionPane.showMessageDialog(null, "Login Failed","Error Meassage",JOptionPane.ERROR_MESSAGE);
            txt1.setText("");
            txt2.setText("");
            txt1.requestFocus();
            }
        } catch (SQLException ex) {
            Logger.getLogger(FrmLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
        }

这是第二堂课:

    if(evt.getKeyChar()==KeyEvent.VK_ENTER ){

        if(txt6.getText().equals(txt7.getText())){
    try {

    stmt.executeQuery("Insert into TbSignUp(FirstName,LastName,Username,Userpassword) values('"+txt3.getText()+"','"+txt4.getText()+"','"+txt5.getText()+"','"+txt7.getText()+"')");

            JOptionPane.showMessageDialog(null, "User Create Successfully", "Congratulation Meassage",JOptionPane.INFORMATION_MESSAGE);
            FrmLogin fl = new FrmLogin();
            fl.setVisible(true);
            this.setVisible(false);

        } catch (SQLException ex) {
            Logger.getLogger(FrmSignUp.class.getName()).log(Level.SEVERE, null, ex);
        }
        }else{
            JOptionPane.showMessageDialog(null, "Password Not Match", "Error Message",JOptionPane.ERROR_MESSAGE);
        }
        }

1 个答案:

答案 0 :(得分:2)

Can not issue data manipulation statements with executeQuery().

您只能在select中执行executeQuery()语句来更新您应该使用的数据库executeUpdate()

stmt.executeUpdate("Insert into TbSignUp(FirstName,LastName,Username,Userpassword) values('"+txt3.getText()+"','"+txt4.getText()+"','"+txt5.getText()+"','"+txt7.getText()+"')");

您应该按照@EJP

的建议使用PreparedStatement