2014-01-12 55 views
1

我写了一些java代码,用于在用户按下按钮时将数据插入SQL Server 2012数据库。当我运行的代码,我得到这个错误:获取“jdbc.SQLServerException:错误语法附近','”执行时出错PreparedStatement

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near ','.

和它说,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

也去改变你的'sa'密码! –

+2

你真的好像没有理解PreparedStatement的要点 –

回答

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(); 
+0

所以它(几乎)是有效的T-SQL? –

+0

@ElliottFrisch除了开放SQL注入攻击之外,是的。 T-SQL使用方括号作为名称的“引号”。 – dasblinkenlight