PreparedStatement在Java中插入

时间:2012-03-08 21:59:18

标签: java prepared-statement

我编写了一个代码,如果按下某个按钮,则应从文本字段中获取值以在数据库中创建记录。代码编译,但当我运行它时,我收到此错误消息:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'From, To, TotalDays, VacationType, Notes, Signature, Date) VALUES('','','','',''' at line 1

有什么建议吗?

    final JButton btnSubmit = new JButton("Submit");
    btnSubmit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {                 
        try {

            String vacationid = text_vacationID.getText();
            String staffid = text_staffID.getText();
            String from = text_from.getText();
            String to = text_to.getText();
            String totaldays = text_totalDays.getText();
            String vacationtype = text_vacationType.getText();
            String notes = textArea.getText();
            String signature = text_signature.getText();
            String date = text_date.getText();


            String sql = "INSERT into vacation (VacationID, StaffID, From, To, TotalDays, VacationType, Notes, Signature, Date) VALUES" + "(?,?,?,?,?,?,?,?,?)";    

            PreparedStatement prest = con.prepareStatement(sql);
            prest.setString(1, vacationid);
            prest.setString(2, staffid);
            prest.setString(3, from);
            prest.setString(4, to);
            prest.setString(5, totaldays);
            prest.setString(6, vacationtype);
            prest.setString(7, notes);
            prest.setString(8, signature);
            prest.setString(9, date);

            prest.executeUpdate();
            JOptionPane.showMessageDialog(frmBookVacation, "Vacation has been booked for Employee with ID: " + vacationid);


        } 

        catch (SQLException e) {
        //System.out.println("Record couldn't be added!");
        e.printStackTrace();
        JOptionPane.showMessageDialog(frmBookVacation, "Vacation couldn't be booked. Please try again.");
        }
        }

        });
    btnSubmit.setBounds(201, 350, 89, 23);
    panel_1.add(btnSubmit);

4 个答案:

答案 0 :(得分:5)

from是SQL中的保留字,需要escape it with backticks(如果启用了ANSI模式,则需要引号)。

String sql = "INSERT into vacation (`VacationID`, `StaffID`, `From`, `To`, `TotalDays`, `VacationType`, `Notes`, `Signature`, `Date`) VALUES" + "(?,?,?,?,?,?,?,?,?)";

我已经在那里完成了所有的列名称,以保持一致性,因为其他几个引擎可能会保留(或者不是)其他几个。

答案 1 :(得分:1)

“From”是一个关键字。请记住,SQL中的关键字不区分大小写。用后面的引号括起来

`From`

答案 2 :(得分:1)

答案 3 :(得分:0)

From是MySQL中的保留字。您还可以在代码中删除表中的所有字段,如下所示:

String sql = "INSERT into vacation VALUES" + "(?,?,?,?,?,?,?,?,?)";    

这应该有效。