当用户按下按钮时,我编写了一些 java 代码将数据插入到 SQL Server 2012 的数据库中。当我运行代码时,我得到这个错误:
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();
}
}
最佳答案
您在 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();
关于java - 执行 PreparedStatement 时得到 "jdbc.SQLServerException: Incorrect syntax near ' ,'"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21070894/