Here is another example on how to read data from a ResultSet
returned by executing an SQL query in a database.
We start by creating a connection to the database. Creates a PreparedStatement
to execute a query to get some data from the books
table.
After executing the PreparedStatement
we will have a ResultSet
object. To iterate all the data in the ResultSet
we call the next()
method in a while-loop. When no more record to read the method return false. The ResultSet
object also provides some methods to read value of the fields, the name of the method is corresponded to the type of data stored on each field of the table.
To read data using the ResultSet
‘s methods (e.g. getString()
, getInt()
, getFloat()
, etc) we can either use the column name, or the column index of the field read in the SQL statement.
Let’s see the complete code snippet below:
package org.kodejava.jdbc;
import java.sql.*;
public class ResultSetExample {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost/kodejava";
String username = "root";
String password = "";
try (Connection connection =
DriverManager.getConnection(url, username, password)) {
String query = "SELECT isbn, title, published_year, price " +
"FROM books";
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// Read values using column name
String isbn = rs.getString("isbn");
String title = rs.getString("title");
int publishedYear = rs.getInt("published_year");
// Read values using column index
double price = rs.getDouble(4);
System.out.printf("%s, %s, %d, %.2f\n", isbn, title,
publishedYear, price);
}
}
}
}
Maven dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023