JAVA:数据库结果集保持返回零行

时间:2011-04-16 21:52:20

标签: java database

我通过使用存根来验证驱动程序正在加载并且正在建立连接。查询数据库的方法正在执行而没有错误,但返回的是5列0行的空结果集(我通过调试验证)。测试数据库中有4列5列,我的查询要求返回所有结果。我可能只是累了......对于我失踪了什么的任何见解?这是查询方法。数据库文件是访问.mdb

public ArrayList fillResults()     {         ArrayList savedData = new ArrayList();         语句stmt = null;         ResultSet results = null;

    try
    {
        stmt = conn.createStatement();
        results = stmt.executeQuery(SELECT_ALL);
        while(results.next())
        {
            for(short i = 0; i < 5; i++)
            {
                savedData.add(results.getString(i));
            }
        }

    }
    catch(SQLException ex)
    {
        JOptionPane.showMessageDialog(null, ex.getMessage() + ": error during retrieval.");
    }
    finally
    {           
        try
        {
            results.close();
            stmt.close();
        } catch (SQLException e){}
    }

    return savedData;
}

1 个答案:

答案 0 :(得分:0)

你不应该归还ResultSet。持久化类不应该包含Swing JOptionPane

试试这样:

package persistence;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class JdbcDemo
{
    private static final String SELECT_SAVED_DATA = "select * from saveData";

    private Connection connection;

    public JdbcDemo(Connection connection)
    {
        this.connection = connection;
    }

    public List<String> getSavedData() throws SQLException
    {
        List<String> savedData = new ArrayList<String>();

        Statement stmt = null;
        ResultSet rs = null;
        try
        {
            stmt = this.connection.createStatement();
            rs = stmt.executeQuery(SELECT_SAVED_DATA);
            while (rs.next())
            {
                savedData.add(rs.getString(1)); // modify this as needed
            }
        }
        finally
        {
            DatabaseUtils.close(rs);
            DatabaseUtils.close(stmt);
        }

        return savedData;
    }
}