【问题标题】:java sql insert preparedstatment errorjava sql插入preparedstatement错误
【发布时间】:2026-01-25 09:50:02
【问题描述】:
String sql = " INSERT INTO `tblservice` (`ServiceID`,`accountID`, `Kind`, `Description`, `Price`, "
        + "`Quantity`, `Total`, `DateAndTime`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setInt(1, this.accountID);
pstm.setString(2, "" + SelectionBox.getSelectedItem());
pstm.setString(3, desc);
pstm.setFloat(4, Float.parseFloat(PriceTF.getText()));
pstm.setFloat(5, Float.parseFloat(QuantityTF.getText()));
pstm.setFloat(6, this.getTotal());
pstm.setDate(7, dateAdded);

pstm.executeUpdate();

错误

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?, ?, ?, ?, ?, ?, ?)' at line 1

【问题讨论】:

  • 问题在哪里?上下文在哪里?我们需要更多信息,以便我们可以尽力帮助您...
  • 错误信息告诉你该怎么做。你有什么问题?
  • 我目前正在使用一个按钮来触发该代码,并且每次我按下该按钮时,它都会一直显示该错误并且没有任何操作触发我的意思是没有插入数据。那不应该是它应该在表中添加新数据,但它不起作用。

标签: java sql jdbc netbeans


【解决方案1】:

例如在查询VALUES (NULL, ...) 中使用setNull 而不是使NULL:

pstm.setNull(1, java.sql.Types.INTEGER);

它将采用您的字段的类型,在此示例中,我认为它是 java.sql.Types.INTEGER 它可以是 java.sql.Types.VARCHAR 或任何 sql type

所以你的查询应该是这样的:

String sql = "INSERT INTO tblservice (ServiceID, accountID, Kind, Description, 
               Price, Quantity, Total, DateAndTime) 
               VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setNull(1, java.sql.Types.INTEGER);
pstm.setInt(2, this.accountID);
....

【讨论】:

  • 谢谢你的回答兄弟。我已经尝试过您的建议,但仍然返回相同的错误。错误发生是因为:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以在第 1 行的“?,?,?,?,?,?,?,?)”附近使用正确的语法
  • 你确定你的字段类型accountID我认为它是你数据库中的一个int而不是一个String,我错了吗? @meltits
  • 我已经更新了下面的语法,但仍然出现同样的错误
  • String sql = " INSERT INTO tblservice (ServiceID,accountID, Kind, Description, Price, Quantity, @9876543345@, @9876)值(?,?,?,?,?,?,?,?)“; PreparedStatement pstm = conn.prepareStatement(sql);
  • @meltits 你设置了pstm.setNull(1, java.sql.Types.INTEGER); 吗?