0

编码:

    Connection connection;
    String url, usernameDB, passwordDB;

    url = "...";
    usernameDB = "...";
    passwordDB = "..."; 

    Class.forName("com.mysql.jdbc.Driver");
    connection = DriverManager.getConnection(url, usernameDB, passwordDB);
    Statement statement = connection.createStatement();

    queryResult = statement.executeQuery(query); 
    boolean moreRecords = queryResult.next();
    if(!moreRecords)
    {
        out.writeBoolean(false);
        out.flush();
    }
    else
    {
        int cols=0;
        out.writeBoolean(true);
        out.flush();
        out.reset(); // line 1
        cols = queryResult.getMetaData().getColumnCount();
        out.writeInt(cols);
        out.flush();
        out.reset(); 
        out.flush();
        out.reset();
        do
        {
            for(int i=1;i<=cols;i++)
            {
                out.writeObject(queryResult.getObject(i)); // line 2
                out.flush();
                out.reset();
            }
            out.writeBoolean(false);
            out.flush();
            out.reset();
        }
        while(queryResult.next());
    }

'out' 是一个 ObjectOutputStream。

当我到达上面代码中的第 1 行时,queryResult 对象会自行重置,当我到达第 2 行时,我得到一个异常:

“java.sql.SQLException:结果集结束后”。

我试图找到一种增加连接超时的方法,但没有找到任何方法。似乎当我到达上面代码中的第 1 行时,我失去了与数据库的连接,从而破坏了我的 queryResult 对象。

有没有办法解决这个问题,或者克隆结果集(使用它的值)?

编辑

此代码在 tomcat 6 中运行,我打开一个 ServerSocket 并为每个连接启动一个新线程,该线程依次执行上面的代码....

4

1 回答 1

0

经过一番研究,我找到了解决方案。

我使用一个CachedRowset对象来保存 ResultSet 及其所有值的副本。

这是更改后的代码:

CachedRowSet cachedResults = new CachedRowSetImpl();

queryResult = statement.executeQuery(query);
cachedResults.populate(queryResult); // this is important!!
boolean moreRecords = cachedResults.next();
if(!moreRecords)
{
    out.writeBoolean(false);
    out.flush();
}
else
{
    int cols=0;
    out.writeBoolean(true);
    out.flush();
    cols = cachedResults.getMetaData().getColumnCount();
    out.writeInt(cols);
    out.flush();
    do
    {
        for(int i=1;i<=cols;i++)
        {
            out.writeObject(cachedResults.getObject(i));
            out.flush();
        }
                    out.writeBoolean(false);
        out.flush();
    }
    while(cachedResults.next());
}
于 2012-03-25T16:46:12.367 回答