JDBC 學習筆記(九)—— ResultSetMetaData


ResultSet 提供了一個 getMetaData() 方法,用來獲取 ResultSet 對應的 ResultSetMetaData 對象:

ResultSetMetaData getMetaData() throws SQLException;

 

MetaData 即元數據,就是描述其他數據的數據。

ResultSetMetaData 封裝了描述 ResultSet 對象的數據,內部提供了大量的方法來分析 ResultSet 的返回信息,其中最常用的有以下三個方法:

    int getColumnCount() throws SQLException;

    String getColumnName(int column) throws SQLException;

    int getColumnType(int column) throws SQLException;
  • getColumnCount: 返回該 ResultSet 的列數量。
  • getColumnName: 返回指定索引的列名。
  • getColumnType: 返回指定索引的列類型。

 

雖然 ResultSetMetaData 對於分析查詢結果有很大的便宜,但是它會消耗一定的系統開銷,所以如果使用 ResultSet 就足以完成對查詢結果的處理,就沒有必要使用 ResultSetMetaData。

 

最后一點需要注意的是,無論是 ResultSet 還是 ResultSetMetaData,都是需要釋放資源的。

換言之,對於查詢結果的分析一定要在釋放資源之前完成,所以以下代碼的寫法是錯誤的:

package com.gerrard.demo;

import com.gerrard.constants.ErrorCode;
import com.gerrard.exception.JdbcSampleException;
import com.gerrard.util.Connector;
import com.gerrard.util.DriverLoader;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public final class TypicalWrongCase {

    public static void main(String[] args) {
        String sql = "SELECT * from STUDENT";
        dealResultSet(executeQuery(sql));
    }

    public static ResultSet executeQuery(String sql) {
        DriverLoader.loadSqliteDriver();
        try (Connection conn = Connector.getSqlConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            return rs;
        } catch (SQLException e) {
            String msg = "Fail to execute QUERY using prepared statement.";
            throw new JdbcSampleException(ErrorCode.EXECUTE_QUERY_FAILURE, msg);
        }
    }

    private static void dealResultSet(ResultSet rs) {
        // do something with ResultSet
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM