-1

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在“firstName”、“lastName”、“email”、“address”、“userName”、“password”附近使用正确的语法)VALUES(第 1 行的“nu”

当我运行我的 gui 将数据输入到表中时,我遇到了上述错误。

我正在使用下面的代码

class registerInterface extends JFrame {

    static final String DATABASE_URL = "jdbc:mysql://localhost:3306/mysql";
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String USERNAME = "root";
    static final String PASSWORD = "root";
    private JTextField jtfFname, jtfLname, jtfAddress1, jtfAddress2, jtfCity, jtfZipcode, jtfState, jtfUsername, jtfPassword, jtfPassConfirm, jtfEmail, jtfdtype;
    private JButton exitButton, backButton, clearButton, submitButton;
    private JMenuItem jmiBack, jmiClear, jmiSubmit, jmiExit, jmiHelp, jmiAbout;
    String first, last, email, address, username, password, dtype;
    
       // launch the application
    public void Create() {

        Connection conn = null;
        try {
            Class.forName(JDBC_DRIVER).newInstance();
            conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);

            PreparedStatement statement = conn.prepareStatement("INSERT INTO person ('firstName', 'lastName', 'email', 'address', 'userName', 'password') "
                    + "VALUES ('" + first + "', '" + last + "', '" + email + "', '" + address + "', '" + username + "', '" + password + ")");
            statement.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    registerInterface() {
        //create menu bar
        JMenuBar regMenuBar = new JMenuBar();

        //set menu bar to the applet
        setJMenuBar(regMenuBar);

        //add menu "operation" to menu bar
        JMenu optionsMenu = new JMenu("Options");
        optionsMenu.setMnemonic('O');
        regMenuBar.add(optionsMenu);

        //add menu "help"
        JMenu helpMenu = new JMenu("Help");
        helpMenu.setMnemonic('H');
        helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
        regMenuBar.add(helpMenu);

        //add menu items with mnemonics to menu "options"
        optionsMenu.add(jmiSubmit = new JMenuItem("Submit", 'S'));
        optionsMenu.add(jmiClear = new JMenuItem("Clear", 'C'));
        optionsMenu.add(jmiBack = new JMenuItem("Back", 'B'));
        optionsMenu.addSeparator();
        optionsMenu.add(jmiExit = new JMenuItem("Exit", 'E'));

        //panel p1 to holds text fields
        JPanel p1 = new JPanel(new GridLayout(11, 11));
        p1.add(new JLabel("First Name: "));
        p1.add(jtfFname = new JTextField(15));
        p1.add(new JLabel("Last Name: "));
        p1.add(jtfLname = new JTextField(15));
        p1.add(new JLabel("Street Address 1: "));
        p1.add(jtfAddress1 = new JTextField(15));
        
        p1.add(new JLabel("E-mail Address: "));
        p1.add(jtfEmail = new JTextField(15));
        p1.add(new JLabel("Username: "));
        p1.add(jtfUsername = new JTextField(15));
        p1.add(new JLabel("Password: "));
        p1.add(jtfPassword = new JPasswordField(15));
        //p1.add(new JLabel("jtfdtype: "));
        //p1.add(jtfdtype = new JTextField(15));


        //panel p2 to holds buttons
        JPanel p2 = new JPanel(new FlowLayout());
        p2.add(exitButton = new JButton("Exit"));
        p2.add(backButton = new JButton("Back"));
        p2.add(clearButton = new JButton("Clear"));
        p2.add(submitButton = new JButton("Submit"));

        //Panel with image??????

        //add panels to frame
        JPanel panel = new JPanel(new GridLayout(2, 1));
        panel.add(p1, BorderLayout.CENTER);
        panel.add(p2, BorderLayout.SOUTH);
        add(panel, BorderLayout.CENTER);


        //listners for exit menuitem and button
        jmiExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        exitButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        //listner for about menuitem
        jmiAbout.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null,
                        "This is the registration panel"
                        + "\n Assignment for University",
                        "About", JOptionPane.INFORMATION_MESSAGE);
            }
        });


        //listners for clear menuitem and button
        jmiClear.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jtfFname.setText("");
                jtfLname.setText("");
                jtfAddress1.setText("");
                
                
                jtfEmail.setText("");
                jtfUsername.setText("");
                jtfPassword.setText("");
            }
        });

        clearButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jtfFname.setText("");
                jtfLname.setText("");
                jtfAddress1.setText("");
  
               
                jtfEmail.setText("");
                jtfUsername.setText("");
                jtfPassword.setText("");
            }
        });

        //action listeners for back buttons and redister menuitem
        backButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Welcome welcome = new Welcome();
                welcome.setVisible(true);
                welcome.setSize(500, 500);
                welcome.setLocationRelativeTo(null);
                registerInterface regFace = new registerInterface();
                regFace.setVisible(false);
                registerInterface.this.dispose();
                registerInterface.this.setVisible(false);
            }
        });

        jmiBack.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Welcome welcome = new Welcome();
                welcome.setVisible(true);
                welcome.setLocationRelativeTo(null);
                registerInterface regFace = new registerInterface();
                regFace.setVisible(false);
                registerInterface.this.dispose();
                registerInterface.this.setVisible(false);

            }
        });

        //action listeners for Login in button and menu item
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String a = jtfFname.getText();
                String b = jtfLname.getText();
                String c = jtfEmail.getText();
                String d = jtfAddress1.getText();
                String u = jtfUsername.getText();
                String f = jtfPassword.getText();
               // String g = jtfdtype.getText();
                
              
                Create();
            }
        });
    }
}

 and this is the table im using

CREATE TABLE PERSON (
    ID SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
    firstName VARCHAR (50) NOT NULL,
    lastName VARCHAR (50) NOT NULL,
    email VARCHAR (50) NOT NULL,
    address VARCHAR (50),
    city VARCHAR (20),
    userName VARCHAR (20) NOT NULL,
    password VARCHAR (20) NOT NULL,
    dtype VARCHAR (20) NOT NULL,
    PRIMARY KEY (ID),
    UNIQUE KEY (email)
            );
4

3 回答 3

1

在执行之前尝试以下方式查看查询以找出错误:

    public void Create(String first, String last, String email, String address, String username, String password) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            Class.forName(JDBC_DRIVER).newInstance();
            conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);

            StringBuilder query = new StringBuilder("INSERT INTO person(firstName, lastName, email, address, userName, password) VALUES(")
                .append("'").append(first).append("',")
                .append("'").append(last).append("',")
                .append("'").append(email).append("',")
                .append("'").append(address).append("',")
                .append("'").append(username).append("',")
                .append("'").append(password).append("'")
                .append(")");

            System.out.println( query.toString());

            statement = conn.prepareStatement( query.toString() );
            statement.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (statement != null) {
                statement.close();
            }

            if (conn != null) {
                conn.close();
            }

        }
    }

您可以像这样更改您的 submitButton 功能:

    //action listeners for Login in button and menu item
    submitButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String fName = jtfFname.getText();
            String lName = jtfLname.getText();
            String email = jtfEmail.getText();
            String address = jtfAddress1.getText();
            String username = jtfUsername.getText();
            String password = jtfPassword.getText();

            Create(fName , lName, email, address, username, password);
        }
    });
于 2013-09-29T07:36:14.533 回答
1

不要以这种方式使用准备好的语句。您的代码容易受到 SQL 注入的攻击。

以这种方式使用准备好的语句:

    PreparedStatement statement = conn.prepareStatement(
          "INSERT INTO person (firstName, lastName, email, address, userName, password) "
          + "VALUES (? , ?, ?, ?, ?, ?)";
        statement.setString( 1, first);
        statement.setString( 2, last );
        statement.setString( 3, email );
        statement.setString( 4, address );
        statement.setString( 5, username );
        statement.setString( 6, password );
        statement.executeUpdate();

这也可以防止一些愚蠢的错误,比如遗漏撇号。

这是一个教程how to use PreparedStatementhttp ://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

于 2013-09-29T07:36:26.627 回答
0

你最后错过'了你的陈述。你的陈述应该是:

 PreparedStatement statement = 
 conn.prepareStatement("INSERT INTO person ('firstName', 'lastName', 'email', 
                      'address', 'userName', 'password') "
                     + "VALUES ('" + first + "', '" + last + "', '" + email + "',
        '" + address + "', '" + username + "', '" + password + "')");
于 2013-09-29T07:31:29.120 回答