MySQL查询通过Java语法错误

时间:2014-11-10 11:38:09

标签: java mysql syntax-error

我有这段代码将记录插入到帐户表中:

String accNumber = jTextField5.getText();
String accName = jTextField4.getText();
String accAddress1 = jTextField3.getText();
String accAddress2 = jTextField2.getText();
String accCity = jTextField6.getText();
String accCounty = jTextField7.getText();
String accPostCode = jTextField9.getText();
String accContact = jTextField8.getText();

String query = "Insert into accounts (AccNo, name, address, address2, address3, City, County, PostCode, contact) values (?, ?, ?, ?, ?, ?, ?, ?, ?)";

try{

    connect.pst = connect.con.prepareStatement(query);
    connect.pst.setString(1, accNumber);
    connect.pst.setString(2, accName);
    connect.pst.setString(3, accAddress1);
    connect.pst.setString(4, accAddress2);
    connect.pst.setString(5, null);
    connect.pst.setString(6, accCity);
    connect.pst.setString(7,accCounty);
    connect.pst.setString(8, accPostCode);
    connect.pst.setString(9, accContact);
    connect.pst.execute();
    JOptionPane.showMessageDialog(null, "Saved");

}catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}

这很好用,并将记录插入到帐户表中。接下来我有这段代码,用于更新包含6个字段的orderstable表;订单号,AccNo,Incvoice号码,描述,金额,增值税。订单号字段已设置为自动递增 代码:

String accNumber = jTextField29.getText();
String invNo = jTextField20.getText();
String description = jTextField21.getText();
String vat = jTextField22.getText();
String amount = jTextField23.getText();

String query = "Insert into orderstable (Order Number, AccNo, Invoice Number, Description, Amount, VAT) values (?, ?, ?, ?, ?, ?)";
try{

    connect.pst = connect.con.prepareStatement(query);
    connect.pst.setString(1, "3");
    connect.pst.setString(2, accNumber);
    connect.pst.setString(3, invNo);
    connect.pst.setString(4, description);
    connect.pst.setString(5, amount);
    connect.pst.setString(6, vat);
    connect.pst.execute();
    JOptionPane.showMessageDialog(null, "Saved");

}catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}

上面的代码返回SQL语法错误。我不知道为什么。这个SQL语法错误的原因是什么?

2 个答案:

答案 0 :(得分:3)

您不能将列名称包含在空格中,如果您这样做,则需要使用反引号

Insert into orderstable 
(`Order Number`, AccNo, `Invoice Number`, Description, Amount, VAT)

点击此处查看详情http://dev.mysql.com/doc/refman/5.0/en/identifiers.html

答案 1 :(得分:0)

自动增量字段order number不应包含在属性部分中。

您的查询应如下所示

String query = "Insert into orderstable (AccNo, Invoice Number, Description, Amount, VAT) values (?, ?, ?, ?, ?)"; 

order number列不应包含在字段列表中,因为它是自动增量