JAVA: Database resultset keep returning zero rows
i verified through the use of stubs that the driver is loading and the connection is being made. my method that queries the database is executing without errors but is returning an empty resultset of 5 columns and 0 rows (which i verified via debug). There are 4 records with 5 columns in the test database and my query asks to return all results. I may just be tired... any insig开发者_StackOverflow社区ht on what im missing? here is the query method. the database file is access .mdb
public ArrayList fillResults() { ArrayList savedData = new ArrayList(); Statement 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;
}
You should NOT be returning a ResultSet
. And a persistence class should not have a Swing JOptionPane
in it.
Try it like this:
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;
}
}
精彩评论