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
    }
}

猜你喜欢

转载自www.cnblogs.com/jing-an-feng-shao/p/9227114.html
今日推荐