Search code examples
javajdbcresultset

Retrieve specific row from access table


I've looked through this forum and searched the web for a solution to my above problem but could not find something that points me in the right direction. Please forgive me if this is a duplication.

I'm working on a java project where my application interacts with an MS Access 2016 database. One of the functions of my program is to query the db for a specific record and display the data of that record in a gui. Here is my code to retrieve the data:

int i = 0;
String q = "select * from QueryData where id=123456"; 
try {
    pstmnt=conn.prepareStatement(q); 
    Object obj ; 
    rs = pstmnt.executeQuery();
    while (rs.next()) {
         obj=rs.getObject(i+1);
         data.add(obj); //where data is a List object i++; 
    }
 } catch ....

Problem is I only get the first value in this record (1st column of record) and there are more data available in the record/row.

Could it be the rs.next() method that is doing this and if so, what should I use to get the next value in this specific record?


Solution

  • ResultSet#next() iterates over the rows in the result set (which, in this case, is just a single row). If you don't know the result set's structure upfront, you can dynamically deduce it from a ResultSetMetaData object:

    int i=0; 
    String q="select * from QueryData where id=123456"; 
    try (PreparedStatement pstmnt = conn.prepareStatement(q);
         ResultSet rs = pstmnt.executeQuery()) {
    
         ResultSetMetaData rsmd = rs.getMetaData();
    
         // Assume it's just one row.
         // If there's more than one, you need a while loop
         if (rs.next()) {
             for (int i = 0; i < rsmd.getColumnCount(); ++i) {
                 data.add(rs.getObject(i + 1));
             }
         }
    }