2013-05-26 35 views
1

我正在嘗試編寫簡單的Java Web應用程序以從數據庫獲取數據。 我需要在不同的數據庫表上運行幾個select查詢。如何使用相同的語句和結果集運行多個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(); 

我只能運行具有相同的語句一個查詢。我怎樣才能用相同的語句執行多個查詢?

+1

可能需要幫助:http://stackoverflow.com/questions/1079 7794/multiple-queries-in-java-in-single-statement –

+0

我得到這樣的數據源:DataSource dataSource =(DataSource)context.lookup(「jdbc/DatabaseName」);如何將allowMultipleQueries標誌添加到該字符串?謝謝。 –

+2

你爲什麼在意?爲什麼使用幾個陳述是一件壞事? –

回答

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(); 
} 

附:將你的Connection,ResultSet和Statement對象封裝在try ... finally塊中是一個好主意,以便確保你可以每次關閉()他們

+2

從Java 7開始,您可以使用* try-with-resources * – millimoose

+0

@ EmanuelSaringan您不覺得這種方法會帶來任何性能開銷嗎? –

2

爲什麼你不能連接表並做1個查詢來獲得所有結果?您的查詢似乎沒有得到優化。舉個例子:從書本其中BOOKID =從書本那裏BOOKID =出價

可以很容易地在一個查詢進行投標
選擇auther

選擇標題:

選擇標題,bookid = bid的書的作者

相關問題