当我尝试执行SQL插入查询时出现错误

问题描述 投票:0回答:2

我尝试通过jframe和Jtext插入查询,但出现此错误:com.microsoft.sqlserver.jdbc.SQLServerException:无效的列名“ A”。(我插入值名称= A,城市= B,街道= c,电话= 0542223)

private static final String SQL2 = "insert into Hospital (name,city,street,phone) values (";
private static final String CONN_URL = "jdbc:sqlserver://localhost:1433;databaseName=MedicalDB;integratedSecurity=true;";
          JLabel name = new JLabel("name");
      JTextField name1 = new JTextField();
      name1.setPreferredSize(new Dimension(100, 30));

      JLabel city = new JLabel("city");
      JTextField city1 = new JTextField();
      city1.setPreferredSize(new Dimension(100, 30));



      JLabel street3 = new JLabel("the street");
      JTextField street4 = new JTextField();
      street4.setPreferredSize(new Dimension(100, 30));



      JLabel Phone = new JLabel("Phone num");
      JTextField Phone1 = new JTextField();
      Phone1.setPreferredSize(new Dimension(100, 30));

                String name = name1.getText();

            String city = city1.getText();

            String street = street4.getText();

            String phone = Phone1.getText();


            Statement stmt1 = con.createStatement();

            System.out.println(phone);

                String theString = SQL2 + name + "," +  city + "," + street +"," + phone + ");";


                stmt1.executeUpdate(theString);

        }
             catch (Exception e1) {
                e1.printStackTrace();
                System.out.println("here5");
            }

        }
java jdbc
2个回答
1
投票

您没有引用要插入的字符串变量,因此数据库将它们解释为列名,然后由于这些列不存在而失败。

避免这种问题和SQL注入攻击漏洞的教科书方法是使用PreparedStatement

PreparedStatement

1
投票

经过更多检查后,我发现了:我刚刚从以下位置更改了代码:

private static final String INSERT_SQL =
    "insert into Hospital (name, city, street, phone) values (?, ?, ?, ?)";

try (ps = con.prepareStatement(INSERT_SQL)) {
    ps.setString(1, name);
    ps.setString(2, city);
    ps.setString(3, street);
    ps.setString(4, phone);
    ps.executeUpdate();
}

至:

String theString = SQL2 + name + "," +  city + "," + street +"," + phone + ");";
© www.soinside.com 2019 - 2024. All rights reserved.