← Back to Chapters

Database Connection (JDBC)

?️ Database Connection (JDBC)

? Quick Overview

JDBC (Java Database Connectivity) is an API in Advance Java that allows Java applications to connect and interact with relational databases such as MySQL, Oracle, PostgreSQL, and SQL Server.

? Key Concepts

  • JDBC Driver
  • Connection
  • Statement / PreparedStatement
  • ResultSet
  • DriverManager

? Syntax & Theory

JDBC works by loading a database driver, establishing a connection, executing SQL queries, and processing the result.

? View Code Example
// Basic steps to connect Java with a database using JDBC
Class.forName("com.mysql.cj.jdbc.Driver");

String url = "jdbc:mysql://localhost:3306/studentdb";
String user = "root";
String password = "root";

Connection con = DriverManager.getConnection(url, user, password);

? Interactive Simulator: Driver Manager

Test your understanding of the JDBC URL format. Try changing the inputs below and click "Test Connection" to see how the DriverManager responds.

 

? Code Example — Complete JDBC Program

? View Code Example
// Example showing database connection and data retrieval using JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DatabaseConnection {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");

Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/studentdb",
"root",
"root"
);

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");

while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}

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

? Live Output / Explanation

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

✅ Tips & Best Practices

  • Always close database connections
  • Use PreparedStatement to prevent SQL Injection
  • Handle exceptions properly
  • Store credentials securely

? Try It Yourself

  • Create a table and insert sample records
  • Modify the query to use WHERE conditions
  • Implement PreparedStatement
  • Connect Java with another database