Helllo 我有一个关于Java和JDBC的问题,我把所有东西都搞定了。我正在创建一个搜索字段,一切都很好但是当搜索字段为空时我得到了我按下搜索没有任何反应。我想要做的是当搜索字段为空时搜索所有内容。
这是我当前的代码atm
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {
Connection connection = FlatFinder.getConnection();
Statement selectStmt = null;
try {
selectStmt = connection.createStatement();
String sql = String.format(
"SELECT * FROM `flats` WHERE Rent BETWEEN %s AND %s AND No_of_rooms BETWEEN %s AND %s",
priceField.getText(),
priceFieldMax.getText(),
roomField.getText(),
roomFieldMax.getText()
);
ResultSet rs = selectStmt.executeQuery(sql);
resultList.setListData(new String[0]);
DefaultListModel m = new DefaultListModel();
while (rs.next()) {
String text = String.format("%s, %d, %s, %s",
rs.getString("Location"),
rs.getInt("No_of_rooms"),
rs.getInt("Rent"),
rs.getString("Owner")
);
m.addElement(text);
}
resultList.setModel(m);
} catch (SQLException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
你有什么想法吗?谢谢!
答案 0 :(得分:0)
最简单的方法是将空输入字符串替换为实际上代表相应字段的无穷大和负无穷大的值。
例如,对于No_of_rooms,您将使用' 0' 0和' 1000'出租你会使用' 0' 0还有一些非常大的数字。
答案 1 :(得分:0)
因为当搜索字段为空时,您的SQL语句将类似于
SELECT * FROM flats WHERE Rent BETWEEN AND AND No_of_rooms BETWEEN AND
您可以直接在SQL Server上运行该语句以查看返回的内容。
如果要返回所有内容,只需使用语句查询(因此您必须检查条件)
SELECT * FROM flats
更新
处理空字段的一个非常简单的例子
String statement = "SELECT * FROM flats";
if (priceField.getText() != null) {
statement = statement.concat("WHERE Rent BETWEEN ").concat(priceField.getText()).concat(" AND");
} else {
statement = statement.concat("WHERE Rent BETWEEN 0 AND");
}
...
and so on
答案 2 :(得分:0)
即,允许用户输入空字符串。然后,在您的代码中执行以下操作:
highPrice = priceField.getText()
If (highPrice == null)
highPrice = "1000000"
// then do the same with the low price
// bound (setting it to zero if the corresponding
// field is null
// the construct your query with BOTH price limits
// so you will change your code such that it will
// ALWAYS include an upper and lower limit
希望有所帮助。