Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Retrieving Data from Databases Using JDBC in Java

Tech May 8 3

JDBC Database Connectivity Setup

JDBC (Java Database Connectivity) provides a standardized API for interacting with relational databases. The first step involves establishing a connection to the database server.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbConnector {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/testdb";
    private static final String USER = "dbuser";
    private static final String PASS = "dbpass";

    public static Connection establish() throws SQLException {
        return DriverManager.getConnection(DB_URL, USER, PASS);
    }
}

Replace the connection parameters with your actual database credentials and endpoint.

Executing Queries and Processing Results

After establishing connectivity, you can execute SQL queries and iterate through the returned data using a PreparedStatement and ResultSet.

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserRepository {
    public static void fetchUserRecords() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rows = null;
        
        try {
            conn = DbConnector.establish();
            String query = "SELECT username, age FROM users WHERE active = ?";
            stmt = conn.prepareStatement(query);
            stmt.setBoolean(1, true);
            rows = stmt.executeQuery();
            
            while (rows.next()) {
                String name = rows.getString("username");
                int userAge = rows.getInt("age");
                System.out.printf("User: %s | Age: %d%n", name, userAge);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            closeQuietly(rows);
            closeQuietly(stmt);
            closeQuietly(conn);
        }
    }
    
    private static void closeQuietly(AutoCloseable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (Exception ignored) {}
        }
    }
}

The PreparedStatement approach prevents SQL injection by parameetrizing query inputs. The ResultSet cursor initially positions before the first row; calling next() advances through each record.

Handling Different Data Types

The ResultSet interface provides type-safe getters for various column types:

Method Return Type Use Case
getString(col) String VARCHAR, TEXT
getInt(col) int INTEGER
getDouble(col) double DECIMAL, FLOAT
getDate(col) java.sql.Date DATE
getBoolean(col) boolean BOOLEAN

Best Practices

Always close resources in a finally block or use try-with-resources (Java 7+) to prevent memory leaks. Maintain a single connection instance per database when possible rather than creating new connections for each query.

Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.