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.
JDBC works by loading a database driver, establishing a connection, executing SQL queries, and processing the result.
// 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);
Test your understanding of the JDBC URL format. Try changing the inputs below and click "Test Connection" to see how the DriverManager responds.
// 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);
}
}
}
The program connects to the database, executes a SELECT query, and prints student records one by one to the console.
PreparedStatement to prevent SQL InjectionPreparedStatement