I am trying to get all data from a table contained in a database, and parse it into a List. I have tried a few different techniques and can't get it working. I am trying to serialize the ResultSet so I can send it over a socket. The code I have got so far is:
public Object readJavaObject(String query, Connection con) throws Exception
{
PreparedStatement stmt = con.prepareStatement(query);
//stmt.setString(1, id);
query_results = stmt.executeQuery();
while (query_results.next())
{
dataObject = query_results.getObject(1);
}
query_results.close();
stmt.close();
return dataObject;
}
public void run()
{
try
{
Class.forName(dbClass);
con = DriverManager.getConnection (dbUrl, user, pass);
query = "SELECT * FROM Bench_table";
dataList = (List) this.readJavaObject(query, con);
con.close();
}
}
I'm not sure what code to write around readJavaObject
. Can anyone help to point out where the issue is?
Thanks for any help.
Take a look at DbUtils (from apache-commons).
If you need a more complex solution for mapping sql results to java objects, take a look at object-relational mapping . In Java the standard is JPA (Java Persistence API), with Hibernate, EclipseLink and OpenJPA as the most famous implementors.
There are several issues with your code.
I recently discovered the CachedRowSet , which does exactly what OP needs. It notably allows to serialize a ResultSet
, and to restore the original when needed.
我不确定您要实现的目标,但是我可以向您介绍DAO(数据访问对象)模式吗?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.