java - INSERT 语句的未知 SQL 问题

标签 java sql

基本上,我正在尝试使用 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/

相关文章:

java - 从单独的方法使用 java awt drawRect 吗?

java - 通过 Java8 函数获取结果的最佳方式是什么?

mysql - 按相关两列分组

mysql - 如何获取mysql中行的百分比

java - 在 JUnit 5 参数化测试中。 CSV 输入。有没有办法通过 Double.NaN、Double.POSITIVE_INFINITY?

java - 我怎样才能拥有从 Java 中的抽象基类型派生的 Singleton?

java - 如何通过 EditText 获取用户输入并对其进行处理

sql - 带子查询的SQL更新语法

mysql - 如何使用 MySQL 在查询中创建条件

sql - Postgresql——其他条件相同,查询(小)整数或浮点值是否比查询(小)字符串值更快?