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.
java.sql packageClick "Run Simulation" to see how data travels through JDBC.
The basic JDBC workflow follows these steps:
// 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);
}
}
}
The program connects to the database, executes a SELECT query, and prints student records row by row in the console.
PreparedStatement to avoid SQL Injection