0
0
JavaHow-ToBeginner · 4 min read

How to Read Data from Database Using Java: Simple Guide

To read data from a database using Java, use the JDBC API by establishing a Connection, creating a Statement, executing a SELECT query, and processing the ResultSet. This lets you fetch rows from the database and use them in your Java program.
📐

Syntax

Here is the basic syntax to read data from a database using Java's JDBC:

  • Load Driver: Load the database driver class.
  • Establish Connection: Connect to the database using DriverManager.getConnection().
  • Create Statement: Create a Statement or PreparedStatement to run SQL queries.
  • Execute Query: Use executeQuery() to run a SELECT statement.
  • Process ResultSet: Loop through the ResultSet to read rows.
  • Close Resources: Always close ResultSet, Statement, and Connection to free resources.
java
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", "user", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM tablename");
while (rs.next()) {
    // read data from rs
}
rs.close();
stmt.close();
conn.close();
💻

Example

This example connects to a MySQL database, reads all rows from a users table, and prints the id and name columns.

java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ReadDatabaseExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/testdb";
        String user = "root";
        String password = "password";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT id, name FROM users");

            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                System.out.println("ID: " + id + ", Name: " + name);
            }

            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Output
ID: 1, Name: Alice ID: 2, Name: Bob ID: 3, Name: Carol
⚠️

Common Pitfalls

  • Not closing resources: Forgetting to close ResultSet, Statement, or Connection can cause memory leaks.
  • Wrong driver or URL: Using incorrect JDBC driver class or database URL causes connection failure.
  • SQL syntax errors: Mistakes in the SQL query will throw exceptions.
  • Ignoring exceptions: Always handle exceptions to know what went wrong.
java
/* Wrong way: Not closing resources */
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
    System.out.println(rs.getString("name"));
}
// No rs.close(), stmt.close(), conn.close()

/* Right way: Use try-with-resources to auto-close */
try (Connection conn2 = DriverManager.getConnection(url, user, password);
     Statement stmt2 = conn2.createStatement();
     ResultSet rs2 = stmt2.executeQuery("SELECT * FROM users")) {
    while (rs2.next()) {
        System.out.println(rs2.getString("name"));
    }
} catch (Exception e) {
    e.printStackTrace();
}
📊

Quick Reference

Remember these key points when reading data from a database in Java:

  • Load the correct JDBC driver for your database.
  • Use DriverManager.getConnection() with the right URL, username, and password.
  • Use Statement or PreparedStatement to run queries.
  • Process the ResultSet row by row using next().
  • Always close your ResultSet, Statement, and Connection to avoid resource leaks.

Key Takeaways

Use JDBC to connect, query, and read data from databases in Java.
Always close database resources to prevent memory leaks.
Handle exceptions to catch connection or SQL errors.
Use the correct driver and connection URL for your database.
Process the ResultSet by looping through rows with next().