【问题标题】:search query and showing the results in a jtable [closed]搜索查询并在 jtable 中显示结果 [关闭]
【发布时间】:2012-04-17 22:16:37
【问题描述】:

我想执行一个搜索查询并在JTable 中显示结果。我有一个JComboBox,用户可以在其中选择要搜索的字段,例如 nameageID

这是我的代码。

try {
    Class.forName("com.mysql.jdbc.Driver");    
    String connectionUrl = "jdbc:mysql://localhost/db?" + "user=root&password=";
    con = DriverManager.getConnection(connectionUrl);
    Statement state = con.createStatement();

    ResultSet result = state.executeQuery("SELECT * FROM db.atelier where '" + 
        jComboBox1.getSelectedItem().toString() + "'='" +
        jTextField1.getText().toString() + "'");

    ResultSetMetaData resultMeta = result.getMetaData();

    while(result.next()){
        model.addRow(new Object[]{result.getObject(1),result.getObject(2)});      
        model.setDataVector(
            new Object[][]{{result.getObject(1),result.getObject(2)},{}},                           
            new Object[]{resultMeta.getColumnName(1),resultMeta.getColumnName(2)});
        }

    jPanel1.revalidate();
    model.fireTableDataChanged();
    this.repaint();
    state.close();
}
catch (SQLException e){
    System.out.println("SQL Exception: "+ e.toString());
}
catch (ClassNotFoundException cE){
    System.out.println("Class Not Found Exception: "+ cE.toString());
}

con=null;

【问题讨论】:

  • 请对代码块使用一致且符合逻辑的缩进。
  • 参见Q&A,了解 SQL 注入。

标签: java mysql swing jtable


【解决方案1】:

应删除组合框所选项目周围的单引号,以使其成为字段名称而不是字符串文字。此外,一个 PreparedStatement,其中文本字段作为附加参数给出,替换 SQL 字符串中的? 更好。这会转义在文本字段中输入的单引号(以及反斜杠等)。

【讨论】:

    【解决方案2】:

    顺便说一句,您构建搜索查询的方式只会将您的应用程序暴露给 SQL 注入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 2020-11-17
      • 1970-01-01
      相关资源
      最近更新 更多