I want to write a class to be able to read data from SQL database. In the class, there should be a method that can read a given database table one row at a time. The data will pass into Java object and user can do something with it. Then user can read the next row and so on.
My codes:
public class DatabaseReader {
String table = "";
protected boolean available;
public boolean isAvailable()
{
return available;
}
public void setTable(String table)
{
this.table = table;
}
public String[] getData()
{
String sql = "SELECT * FROM "+table+";";
Connection con = getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rm = rs.getMetaData();
int count = rm.getColumnCount();
/**
* so I don't know what to do in here
* is there a better way to keep track of what rows already been read?
*/
if (rs.next()) {
for (int i = 1; i <= count; i++) {
System.out.print(rs.getString(i)+" , ");
}
System.out.println();
available = true;
} else {
available = false;
}
}
}
I assume user can do the following to get data one at a time:
DatabaseReader reader = new DatabaseReader();
reader.setTable("Product"); // assume Product table contains ID, name, price, etc.
while (reader.isAvailable) {
String[] data = getData();
Product product = new Product(data);
// add to a list of products or they can do something else
}
// maybe calculate total price of all products or whatever
The only way I can think of is keep a local variable for ResultSet and use rs.next() until it is done. But I am not sure if that is a good way to do. Is there any better way to do what I want without using ResultSet? I just want to read data from table one at a time. Thanks.