← Back to Chapters

JDBC Introduction

☕ JDBC Introduction

? Quick Overview

JDBC (Java Database Connectivity) is a standard Java API that allows Java applications to interact with relational databases. It acts as a bridge between Java programs and databases like MySQL, Oracle, PostgreSQL, and others.

? Key Concepts

  • JDBC is part of Advance Java
  • It provides classes and interfaces in java.sql package
  • Used to perform CRUD operations
  • Database-independent API
  • Works using JDBC Drivers

⚙️ Interactive Workflow

Click "Run Simulation" to see how data travels through JDBC.

Java App
 
? Driver
 
?️ Database
Status: Idle

? Syntax / Theory

The basic JDBC workflow follows these steps:

  1. Load the JDBC Driver
  2. Establish a Connection
  3. Create a Statement
  4. Execute SQL Query
  5. Process the Result
  6. Close the Connection

? Code Example(s)

? View Code Example
// Step 1: Import JDBC package
import java.sql.*;

// Step 2: Main class
public class JdbcDemo {

// Step 3: Main method
public static void main(String[] args) {

// Step 4: Database connection variables
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "root";

try {

// Step 5: Load JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Step 6: Create connection
Connection con = DriverManager.getConnection(url, user, password);

// Step 7: Create statement
Statement stmt = con.createStatement();

// Step 8: Execute query
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

// Step 9: Process result
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}

// Step 10: Close connection
con.close();

} catch (Exception e) {
System.out.println(e);
}
}
}

? Live Output / Explanation

Expected Output

The program connects to the database, executes a SELECT query, and prints student records row by row in the console.

✅ Tips & Best Practices

  • Always close database connections
  • Use PreparedStatement to avoid SQL Injection
  • Handle exceptions properly
  • Do not hard-code credentials in production

? Try It Yourself

  • Connect JDBC with another database (Oracle/PostgreSQL)
  • Write an INSERT query using JDBC
  • Convert Statement to PreparedStatement
  • Display records using column names