1. ResultSet class.
Now, we are connected to the database, is time to start asking for information to the DBMS. This information will be in form of queries (SQL) or others methods, but almost 90% of times, as the SQL's, the information returned is in a tabular format. Tabular formats are well known because programs like MySQL Workbench or DBeaver show data in these way.
In Java, the class who allow to works with data in tabular format coming from databases is called Resultset. A Resultset is composed by a table (rows and columns) and a pointer to a row, called cursor.

- When we retrieve data from databases, the information is stored in the table, and the cursor points to an imaginary void row called
beforeFisrt. Resultsetcontains a special method callednext(), that do two actions:- Returns
trueif exists a data row after the current row pointed by the cursor, andfalseotherwise. - Push forward the cursor, and points to the next row.
- When a
Resultsetcursor returnfalse, is because all rows have been visited, and now, the cursor is pointing to another imaginary row calledafterLast
When the cursor is pointing a real row, is when we can retrieve data of the columns of the current row. We can use a special and overloaded method, as follows:
getXXX(int columnPosition)\(\rightarrow\) return the data, whereXXXis a datatype (Int, Float, Double, String, etc.) of the position of the column, starting in 1.getXXX(String columnName)\(\rightarrow\) return the data, whereXXXis a datatype (Int, Float, Double, String, etc.) of the column with the given name.
Danger
Take into account:
- The columns start in 1 instead of 0, unlike arrays
- If you do not know the data type of a column, you can use
getObjectand it returns a genericObject. - These methods could throw
SQLException, if the column rank or name is out of rank or not exists.
1.1. ResulSetMetaData
ResultSets from of a query also have a set of metadata. This metadata can be obtained using the ResultSetMetaData. Most relevant methods of this class are:
int getColumnCount()\(\rightarrow\) Gets the number of columns in the ResultSet.String getColumnName(index)\(\rightarrow\) Gets the name of the column indicated in the index (remember that first is 1).String getColumnTypeName(index)\(\rightarrow\) Gets the type of the column
ResulSetMetaData is obtained from each previously generated ResultSet, with getMetaData() method.
1.2. ResultSet algorithm
Regardless the data content of your ResultSet, the way in we should work is as follows:
| Java | |
|---|---|
Be notice than:
- Inside the while loop you don't need to call
next()again. You skip one row otherwise. - When the last row were processed,
next()returnfalse, and the loop finish.
1.3. Sample
In this block of code let's go to see a brief sample to run a query (Select * from table). We will see queries in next sections.