2

我正在尝试编写简单的 Java Web 应用程序来从数据库中获取数据。我需要在不同的数据库表上运行几个选择查询。

String queryOne = "select firstname from employees where empid = id";
String queryOne = "select title from books where bookid = bid";
String queryOne = "select auther from books where bookid = bid";

我试着这样做:

Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet rs1 = statement.executeQuery(queryOne);

while (rs1.nest()) {
String firstName = rs1.getString(1);
}
statement.close();
connection.close();

我只能使用相同的语句运行一个查询。如何使用相同的语句执行多个查询?

4

2 回答 2

5

您也许可以将所需的查询存储在一个数组中并像这样遍历它:

Connection conn = dataSource.getConnection();
try {
  Statement stmt = conn.createStatement();
  try {
    for (String q : queries) {  //queries is an array containing the 3 queries
      ResultSet rset = statement.executeQuery(q);
      try {
        rset.getString(1);
      } finally {
        rset.close();
      }
    }
  } finally {
    stmt.close();
  }
} finally {
  conn.close();
}

PS 最好将您的 Connection、ResultSet 和 Statement 对象包含在 try...finally 块中,以确保您每次都能关闭()它们。

于 2013-05-26T14:40:14.587 回答
2

为什么不能加入表并进行 1 次查询以获取所有结果?您的查询似乎非常未优化。举个例子:

从 bookid = bid 的书籍中选择标题 从 bookid = bid
的书籍中选择作者

可以在一个查询中轻松完成:

从 bookid = bid 的书籍中选择标题、作者

于 2013-05-26T14:42:26.940 回答