Java

JDBC Basic

Java Database Connectivity. Learn how to connect Java to SQL databases.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Java Database Connectivity. Learn how to connect Java to SQL databases. This hands-on tutorial focuses on practical implementation of jdbc basic concepts.

JDBC (Java Database Connectivity)

JDBC is an API that allows Java to interact with databases like MySQL, PostgreSQL, and Oracle.

Architecture

  1. Java Application: Your code.
  2. JDBC Driver: Library specific to the DB (e.g., mysql-connector-java).
  3. Database: The actual storage.

Steps to Connect

  1. Load Driver: Class.forName("com.mysql.cj.jdbc.Driver");
  2. Create Connection: DriverManager.getConnection(url, user, pass);
  3. Create Statement: con.createStatement();
  4. Execute Query: stmt.executeQuery(sql);
  5. Process ResultSet: Loop through data.
  6. Close Connection.

Code Example

import java.sql.*;

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

        try {
            Connection con = DriverManager.getConnection(url, user, pass);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM users");

            while(rs.next()) {
                System.out.println(rs.getString("username"));
            }
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

[!WARNING] Always assume user input is malicious! Use PreparedStatement to prevent SQL Injection.

PreparedStatement

Unlike Statement, PreparedStatement pre-compiles the SQL and accepts parameters safely.

PreparedStatement pstmt = con.prepareStatement("SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 101);
ResultSet rs = pstmt.executeQuery();

AI Mentor

Confused about "Java JDBC architecture, connection steps and PreparedStatements"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 3

Which interface is used to execute queries?

Result
Statement
Driver

Next Steps

Raw JDBC is verbose. In Module 16, we'll see how Spring Boot makes this painless.