执行PreparedStatement时出现“jdbc.SQLServerException:'附近的语法错误','”错误

时间:2014-01-12 03:17:23

标签: java sql sql-server jdbc

我写了一些java代码,当用户按下按钮时将数据插入到SQL Server 2012的数据库中。当我运行代码时,我收到此错误:

  

com.microsoft.sqlserver.jdbc.SQLServerException:','附近的语法不正确。

它说sqlstatement.executeUpdate();行导致了错误。我知道这条线不是问题。问题是我的SQL查询,但我找不到我的查询是如何错误的。你能帮帮我吗?

这里是代码

count++;
for(int count = 0; count < table_1.getRowCount(); count++){
    try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
          Connection dbconbt8 = DriverManager.getConnection("" +"jdbc:sqlserver://localhost;databaseName=Store;user=sa;password=XXXXXX");
          String sqlQ = "INSERT INTO [dbo].[Transaction]([TransactionID],[ProductID]"+
           ",[TotalPrice]) VALUES ("+count+"','"+table_1.getValueAt(count, 0).toString()+"','"+sumprice+ "') ";
           PreparedStatement sqlstatement = dbconbt8.prepareStatement(sqlQ);
           sqlstatement.executeUpdate();
                       sqlstatement.close();
                       dbconbt8.close();
            } catch (SQLException e1) {

                          e1.printStackTrace();
                      } catch (ClassNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                  }

1 个答案:

答案 0 :(得分:7)

您在VALUES (之后缺少单引号 - 这应该可以解决问题:

String sqlQ = "INSERT INTO [dbo].[Transaction]([TransactionID],[ProductID]"+
    ",[TotalPrice]) VALUES ('"+count+"','"+table_1.getValueAt(count, 0).toString()+"','"+sumprice+ "') ";
--                          ^
--                        Here

但是,这是一个错误的修复:您应该使用参数重写查询,以便引用数据的问题完全无关:

String sqlQ = "INSERT INTO [dbo].[Transaction]([TransactionID],[ProductID],[TotalPrice]) VALUES (?,?,?) ";
PreparedStatement sqlstatement = dbconbt8.prepareStatement(sqlQ);
sqlstatement.setInt(1, count);
sqlstatement.setString(2, table_1.getValueAt(count, 0).toString());
sqlstatement.setInt(3, sumprice);
sqlstatement.executeUpdate();
相关问题