简体   繁体   中英

I cannot connect Java to MySQL

I have to classes that connect to the same Database in MySQL, the first class I've connected was okay, but the second class that connect to the same table is show an error message like this

Can not issue data manipulation statements with executeQuery() .

What's wrong? This is the first class code which is have no error:

    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);
        }
        }

This is the second class:

    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);
        }
        }

Can not issue data manipulation statements with executeQuery().

You can only perform select statement in executeQuery() to update database you should use executeUpdate()

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

And You should use PreparedStatement as suggested by @EJP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM