我正在尝试编写简单的Java Web应用程序来从数据库中获取数据。 我需要在不同的数据库表上运行几个select查询。
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();
我只能使用相同的语句运行一个查询。如何使用相同的语句执行多个查询?
答案 0 :(得分:4)
您可以将所需的查询存储在数组中,并像下面这样迭代:
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();
}
P.S。最好将Connection,ResultSet和Statement对象放在try ... finally块中,以确保您能够每次关闭()。
答案 1 :(得分:2)
为什么你不能连接表并进行1次查询以获得所有结果?您的查询似乎非常不优化。举个例子:
从bookid = bid
的图书中选择auther
的书籍中选择标题 从bookid = bid
可以在一个查询中轻松完成:
从书籍中选择标题,作者bookid = bid