了解仅转发结果集 [英] Understanding Forward Only ResultSet

查看:223
本文介绍了了解仅转发结果集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mysql数据库中有一个表,其中有一些行可用.我想从ResultSet仅转发的jdbc程序中的表中检索数据.我的代码是:

I have a table in mysql database where some rows are available. I want to retrieve the data from table in my jdbc program where the ResultSet is forward only. My code is:

import java.sql.*;

public class Test1 {
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Connection con=null;
        Statement st=null;
        ResultSet rs=null;
        int id=0;
        String name=null;
        try {
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hiitstudents","root", "rustyiron");
            st=con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.TYPE_SCROLL_INSENSITIVE);
            String query="select * from students";
            rs=st.executeQuery(query);
            while(rs.next()){
                id=rs.getInt(1);
                name=rs.getString(2);
                System.out.println(id+"\t"+name);
            }               ;
            while(rs.previous()){
                id=rs.getInt(1);
                name=rs.getString(2);
                System.out.println(id+"\t"+name);
            }
            } catch (SQLException e) {
                e.printStackTrace();
        }finally{
            try{
                if(rs!=null)
                    rs.close();

                if(st!=null)
                    st.close();

                if(con!=null)
                    con.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
    }
}

,但是由于默认结果集是仅转发的,因此我们无法在其中调用previous(),否则它将不起作用,但是在我的程序中这样做也将以相反的顺序检索数据.我的代码有什么问题?

but as the default result sets are forward only we cannot call previous() in it or it should not work, but doing so in my program retrieves the data in reverse order also. What is the problem in my code?

推荐答案

这是MySQL处理它的方式,其他数据库的行为可能有所不同.

This is how MySQL handles it, other databases may behave differently.

默认情况下,完全检索ResultSet并将其存储在内存中.

By default, ResultSets are completely retrieved and stored in memory.

如果您正在使用具有大量行的ResultSet或 较大的值,并且无法在JVM中为内存分配堆空间 必需,您可以告诉驱动程序将结果流回一行 一次.

If you are working with ResultSets that have a large number of rows or large values and cannot allocate heap space in your JVM for the memory required, you can tell the driver to stream the results back one row at a time.

要启用此功能,请在 如下方式:

To enable this functionality, create a Statement instance in the following manner:

stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
              java.sql.ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);

Connector/J参考实施说明

这篇关于了解仅转发结果集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆