[软件设计/软件工程] SQLServerException: 无效的列名 尝试执行 SQL 插入查询时

[复制链接]
发表于 2022-5-3 10:16:49
问题
我正在尝试通过 jframe 和 Jtext 插入查询,但出现以下错误:

我插入值 ??name=A、city=B、street=c、phone=0542223。
  1. private static final String SQL2 = "insert into Hospital (name,city,street,phone) values (";
  2. private static final String CONN_URL = "jdbc:sqlserver://localhost:1433;databaseName=MedicalDB;integratedSecurity=true;";
  3.           JLabel name = new JLabel("name");
  4.       JTextField name1 = new JTextField();
  5.       name1.setPreferredSize(new Dimension(100, 30));

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

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

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

  15.       String name = name1.getText();
  16.       String city = city1.getText();
  17.       String street = street4.getText();
  18.       String phone = Phone1.getText();

  19.       Statement stmt1 = con.createStatement();
  20.       System.out.println(phone);

  21.       String theString = SQL2 + name + "," +  city + "," + street +"," + phone + ");";
  22.       stmt1.executeUpdate(theString);
  23.     }
  24.     catch (Exception e1) {
  25.         e1.printStackTrace();
  26.         System.out.println("here5");
  27.     }
  28. }
复制代码

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

避免这个问题和 SQL 注入漏洞的经典方法是使用 PreparedStatement :
  1. private static final String INSERT_SQL =
  2.     "insert into Hospital (name, city, street, phone) values (?, ?, ?, ?)";

  3. try (ps = con.prepareStatement(INSERT_SQL)) {
  4.     ps.setString(1, name);
  5.     ps.setString(2, city);
  6.     ps.setString(3, street);
  7.     ps.setString(4, phone);
  8.     ps.executeUpdate();
  9. }
复制代码






上一篇:渐变不平滑
下一篇:用于 NLP 实践的有效数据集

使用道具 举报

Archiver|手机版|小黑屋|吾爱开源 |网站地图

Copyright 2011 - 2012 Lnqq.NET.All Rights Reserved( ICP备案粤ICP备14042591号-1粤ICP14042591号 )

关于本站 - 版权申明 - 侵删联系 - Ln Studio! - 广告联系

本站资源来自互联网,仅供用户测试使用,相关版权归原作者所有

快速回复 返回顶部 返回列表