26.3.1.2. 使用語句以執行SQL |
| 發布時間: 2012/8/20 17:44:56 |
|
使用語句,可執行基本的SQL查詢,并通過下面介紹的ResultSet類檢索結果。 計算機愛好者www.boydavid.com 要想創建語句實例,應通過前面介紹的DriverManager.getConnection()或DataSource.getConnection()方法之一,在檢索的連接對象上調用createStatement()方法。 一旦擁有了語句實例,可以與希望使用的SQL一起通過調用executeQuery(String)方法執行SELECT查詢。 計算機愛好者www.boydavid.com 要想更新數據庫中的數據,可使用executeUpdate(String SQL)方法。該方法將返回受更新語句影響的行數。 如果你事先不清楚SQL語句是SELECT或UPDATE/INSERT,應使用execute(String SQL)方法。如果SQL查詢是SELECT,本方法將返回“真”,如果SQL查詢是UPDATE/INSERT/DELETE,本方法將返回“假”。如果是SELECT查詢,能夠通過調用getResultSet()方法檢索結果。如果是UPDATE/INSERT/DELETE查詢,能夠通過在語句實例上調用getUpdateCount()檢索受影響的行計數。
// assume conn is an already created JDBC connection
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT foo FROM bar");
// or alternatively, if you don't know ahead of time that
// the query will be a SELECT...
if (stmt.execute("SELECT foo FROM bar")) {
rs = stmt.getResultSet();
}
// Now do something with the ResultSet ....
} finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { // ignore }
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
} 計算機愛好者
本文出自:億恩科技【www.endtimedelusion.com】 |
京公網安備41019702002023號