问题
我正在尝试通过 jframe 和 Jtext 插入查询,但出现以下错误:
我插入值 ??name=A、city=B、street=c、phone=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");
- }
- }
复制代码
回答
您没有引用要插入的字符串变量,因此数据库将它们解释为列名,然后由于这些列不存在而失败。
避免这个问题和 SQL 注入漏洞的经典方法是使用 PreparedStatement :
- 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();
- }
复制代码
|