2012-04-17 60 views
0

我想執行搜索查詢並在JTable中顯示結果。我有一個JComboBox,用戶可以選擇領域的搜索,如年齡,或ID搜索查詢並在jtable中顯示結果

這是我的代碼。

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; 
+1

你的問題是什麼? – ControlAltDel 2012-04-17 22:18:59

+1

請爲代碼塊使用一致的邏輯縮進。 – 2012-04-18 04:38:51

+0

另請參閱有關SQL注入的[Q&A](http://stackoverflow.com/q/332365/230513)。 – trashgod 2012-04-18 05:49:05

回答

1

順便說一下,您構建搜索查詢的方式只會將您的應用程序暴露給SQL注入。

2

應該刪除組合框所選項目周圍的單引號,以使它們成爲字段名稱而不是字符串文字。此外,一個PreparedStatement,其中文本字段作爲附加參數給出,替換SQL字符串中的?更好。這可以避免在文本字段中輸入的單引號(和反斜槓等)。