2017-04-07 35 views
-4
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(); 

錯誤Java的SQL INSERT preparedstatment錯誤

在查詢
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 
+1

在哪裏的問題?上下文在哪裏?我們需要更多的信息,所以我們可以嘗試幫助你... – leobelones

+2

錯誤消息告訴你該怎麼做。你的問題是什麼? – betseyb

+0

我目前正在使用一個按鈕來觸發該代碼,並且每次我按下按鈕時,它都會繼續顯示該錯誤,並且沒有任何操作觸發我的意思是沒有數據正在被插入。這不應該是它應該在表中添加新的數據,但它不起作用。 – meltits

回答

0

反而讓空的VALUES (NULL, ...)使用setNull例如:

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

感謝您的回答。我已經嘗試了您的建議,但它仍然返回錯誤.error發生的原因是:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL語法中有錯誤;請檢查第1行 – meltits

+0

附近'?,?,?,?,?,?,?,?'附近使用的正確語法對應的MariaDB服務器版本的手冊。您確定您的字段類型爲accountID '我認爲它是你的數據庫中的一個整數,而不是一個字符串,我錯了? @meltits –

+0

我已經更新下面的語法,但仍然出現同樣的錯誤 – meltits