我有一个包含表格和不同文本字段的表单。我想进行多参数搜索,但我的方法searchPlayer
仅在填写了所有文本字段时才有效。即使我没有填充一个字段(但其他字段已填满),它也无法工作并返回空表。
如果我填写了一些字段,但是不是所有字段,我应该改变什么才能使搜索成为可能?
private static String SEARCH_PLAYER =
"SELECT * FROM fbdb.Players WHERE Number_of_player= ? "
+ "and Full_name LIKE ? "
+ "and Playing_position LIKE ? "
+ "and Height LIKE ? and Weight LIKE ? "
+ "and Nationality LIKE ? and Date_birth LIKE ?";
public String ifnull(String s){
if (s==null){
return "%";
}
return s;
}
public JTable searchPlayer(JTable table, JTextField tfNumOfPlayer,
JTextField tfNamePlayer,
JTextField tfPlayingPosition,
JTextField tfHeight,
JTextField tfWeight,
JTextField tfNationality,
JTextField tfDateBirth) throws SQLException {
PreparedStatement pstm = con.prepareStatement(SEARCH_PLAYER);
pstm.setString (1, ifnull(tfNumOfPlayer.getText()));
pstm.setString (2, ifnull(tfNamePlayer.getText()));
pstm.setString (3, ifnull(tfPlayingPosition.getText()));
pstm.setString (4, ifnull(tfHeight.getText()));
pstm.setString (5, ifnull(tfWeight.getText()));
pstm.setString (6, ifnull(tfNationality.getText()));
pstm.setString (7, ifnull(tfDateBirth.getText()));
ResultSet rs=pstm.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
Vector<Object> data = new Vector<Object>();
Vector<String> columnNames = new Vector<String>();
for (int n = 1; n <= rsmd.getColumnCount(); n++) {
columnNames.add(rsmd.getColumnName(n));
}
while (rs.next()){
Vector<Object> row = new Vector<Object>();
for (int n = 1; n <= rsmd.getColumnCount(); n++) {
row.add(rs.getObject(n));
}
data.add(row);
}
DefaultTableModel dtm = new DefaultTableModel(data,columnNames);
table.setModel(dtm);
return table;
}