-1
final JComboBox destination= new JComboBox();
destination.setModel(new DefaultComboBoxModel(new String[] {"city1", "city2", "city3"}));
destination.setBounds(413, 11, 147, 20);
int selectedIndex1=destination.getSelectedIndex();
contentPane.add(destination);

final JComboBox departure= new JComboBox();
departure.setModel(new DefaultComboBoxModel(new String[] {"city1", "city2", "city3"}));
departure.setBounds(413, 11, 147, 20);
int selectedIndex1=departure.getSelectedIndex();
contentPane.add(departure);

我正在为我的家庭作业编写一个巴士预订系统,但我无法用 Java 编写正确的 SQL 查询。

我有 3 个组合框。

我想编写一个 SQL 查询来显示可用的公交车及其时间。我的意思是这样的:

select busid,bustime
from table1
where des=destination.getSelectedItem()
   && dep=departure.getSelectedItem()
   && date=date.getSelectedItem()

你能帮我吗?

4

1 回答 1

2

我建议您花时间阅读JDBC跟踪...

您的查询仍需要正确“引用”

String query = "select busid,bustime from table1 where des='" + destination.getSelectedItem() + "' AND dep='" + departure.getSelectedItem() + "' AND date='" + date.getSelectedItem() + '";

它已经开始了一段时间,但我不记得&&是 SQL 中的有效运算符......

当然,你真的应该使用准备好的语句

PreparedStatement stmt = null;
try {
    stmt = con.prepareStatement("select busid,bustime from table1 where des=? AND dep=? AND date=?");
    stmt.setString(1, destination.getSelectedItem());
    stmt.setString(2, departure.getSelectedItem());
    // I'm assuming this is String, but it could be a Date
    stmt.setString(3, date.getSelectedItem());

    stmt.execute();
} catch (SQLException exp) {
    exp.printStackTrace();
} finally {
    try {
        stmt.close();
    } catch (Exception exp) {
    }
}
于 2012-12-30T20:16:51.110 回答