Connections
Description
A Connection represents a database session.
Explanation
DriverManager can create one from a database URL and credentials.
Example
java.sql.Connection con = java.sql.DriverManager.getConnection(url, user, password);← Chapter 10 — Threads, Networking & JDBC
mixed
JDBC is Java's standard API for working with relational databases. A JDBC driver connects Java to a specific database system such as MySQL or PostgreSQL.
Use PreparedStatement for values supplied by users or variables. It separates SQL code from data and helps prevent SQL injection.
A Connection represents a database session.
DriverManager can create one from a database URL and credentials.
java.sql.Connection con = java.sql.DriverManager.getConnection(url, user, password);PreparedStatement safely binds values.
Question marks mark values that are set separately.
statement.setString(1, "Aditi");Use try-with-resources for Connection, PreparedStatement, and ResultSet so they close even when an error occurs. Store credentials outside source code, for example in environment-based configuration.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JdbcDemo {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/school";
try (Connection con = DriverManager.getConnection(url, "user", "password");
PreparedStatement statement = con.prepareStatement("SELECT * FROM students WHERE name = ?")) {
statement.setString(1, "Aditi");
System.out.println("Query prepared");
}
}
}