-1

I would like to execute a search query and show the results in a JTable. I have a JComboBox where the user can choose the field to search in, such as name, age, or ID.

This is my code.

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;
wattostudios
  • 8,666
  • 13
  • 43
  • 57

2 Answers2

2

The single quotes around the combobox's selected item should be removed, to make them field names instead of string literals. Furthermore a PreparedStatement, where the text field is given as an additional parameter replacing ? in the SQL string is better. That escapes single quotes entered in the text field (and backslashes and so on).

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

By the way, the way you're building your search query will just expose your application to SQL injection.

kyiu
  • 1,926
  • 1
  • 24
  • 30