文件首頁
MySQL Connector/J 開發人員指南
相關文件 下載本手冊
PDF (美國信紙) - 1.2Mb
PDF (A4) - 1.2Mb


MySQL Connector/J 開發人員指南  /  JDBC 概念  /  使用 JDBC Statement 物件執行 SQL

7.2 使用 JDBC Statement 物件執行 SQL

Statement 物件可讓您執行基本 SQL 查詢,並透過 ResultSet 類別擷取結果,稍後會說明該類別。

若要建立 Statement 執行個體,請在您使用先前描述的 DriverManager.getConnection()DataSource.getConnection() 方法之一擷取的 Connection 物件上呼叫 createStatement() 方法。

一旦您有了 Statement 執行個體,您可以透過呼叫 executeQuery(String) 方法並使用您要使用的 SQL 來執行 SELECT 查詢。

若要更新資料庫中的資料,請使用 executeUpdate(String SQL) 方法。這個方法會傳回更新陳述式比對的資料列數,而不是修改的資料列數。

如果您事先不知道 SQL 陳述式是 SELECT 還是 UPDATE/INSERT,您可以使用 execute(String SQL) 方法。如果 SQL 查詢是 SELECT,這個方法會傳回 true,如果它是 UPDATEINSERTDELETE 陳述式,則會傳回 false。如果陳述式是 SELECT 查詢,您可以透過呼叫 getResultSet() 方法來擷取結果。如果陳述式是 UPDATEINSERTDELETE 陳述式,您可以透過在 Statement 執行個體上呼叫 getUpdateCount() 來擷取受影響的資料列計數。

範例 7.2 Connector/J:使用 java.sql.Statement 執行 SELECT 查詢

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

// assume that conn is an already created JDBC connection (see previous examples)

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 ....
}
catch (SQLException ex){
    // handle any errors
    System.out.println("SQLException: " + ex.getMessage());
    System.out.println("SQLState: " + ex.getSQLState());
    System.out.println("VendorError: " + ex.getErrorCode());
}
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;
    }
}