基本上,我正在尝试使用 getSelectRow 的值更新数据库表。正如您所看到的,查询找到了正确的数据,但在实际尝试将其添加到数据库时遇到了巨大的问题。
错误出在SQL语法上,但我不知道哪里出错了。请帮忙。
这是它执行的查询,但我不知道为什么它不更新表。
INSERT INTO customerdetails
FName = 'Tim'
AND SName = 'Cooley'
AND Address = '52 Buckminster Drive Dorridge Solihull West Mids'
AND Postcode = 'B93 8PG'
Java代码:
private void sendBtnMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
int insertRow = newOrderTbl.getSelectedRow();
int col2 = 0;
String sql3 = "INSERT INTO customerdetails VALUES "
+ "FName = '" + newOrderTbl.getValueAt(insertRow, col2) +"'"
+ "AND SName = '" + newOrderTbl.getValueAt(insertRow, col2+1) +"'"
+ "AND Address = '" + newOrderTbl.getValueAt(insertRow, col2+2) +"'"
+ "AND Postcode = '" + newOrderTbl.getValueAt(insertRow, col2+3) +"'";
System.out.println(sql3);
try{
pst = conn.prepareStatement(sql3);
pst.executeUpdate(sql3);
JOptionPane.showMessageDialog(null, "Deleted");
CustomerTable();
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
最佳答案
首先,您的 SQL 语法是错误的(至少对于您的数据库引擎来说它是非标准 SQL 语法)。其次,您的代码容易受到 SQL 注入(inject)攻击。
为了解决这两个问题,您应该使用 PreparedStatement
(您的做法是错误的)。您的代码的基本示例:
String sql = "INSERT INTO customerdetails (FName, SName, Address, Postcode) VALUES (?, ?, ?,?)";
PreparedStatement pst = conn.prepareStatemtnt(sql);
pst.setString(1, newOrderTbl.getValueAt(insertRow, col2));
pst.setString(2, newOrderTbl.getValueAt(insertRow, col2+1));
pst.setString(3, newOrderTbl.getValueAt(insertRow, col2+2));
pst.setString(4, newOrderTbl.getValueAt(insertRow, col2+3));
pst.executeUpdate();
//rest of code...
假设您的 SQL 语法有效,那么您应该将值作为参数传递,类似于前面的示例:
String sql3 = "INSERT INTO customerdetails VALUES "
+ "FName = ?"
+ "AND SName = ?"
+ "AND Address = ?"
+ "AND Postcode = ?"
pst = conn.prepareStatement(sql3);
pst.setString(1, newOrderTbl.getValueAt(insertRow, col2));
pst.setString(2, newOrderTbl.getValueAt(insertRow, col2+1));
pst.setString(3, newOrderTbl.getValueAt(insertRow, col2+2));
pst.setString(4, newOrderTbl.getValueAt(insertRow, col2+3));
pst.executeUpdate();
//rest of code...
关于java - INSERT 语句的未知 SQL 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15731540/