JDBC
Li Wei
JDBC
JDBC
Overview
JDBC (Java DataBase Connectivity) is a Java API for executing SQL statements. It provides a unified way to access various relational databases and consists of a set of classes and interfaces written in Java.
JDBC is an official Java specification (set of interfaces) that helps developers quickly implement connections to different relational databases.
Core Classes
DriverManager
DriverManager: the driver management object.
Register a driver:
- Register the given driver:
public static void registerDriver(Driver driver) - Code syntax:
Class.forName("com.mysql.jdbc.Driver) com.mysql.jdbc.Drivercontains a static initializer block- No need to call a static method on DriverManager
registerDriver; when the Driver class is used, its static block runs automatically to register the driver - A
java.sql.Driverconfiguration file exists under the JAR’sMETA-INFdirectory, specifyingcom.mysql.jdbc.Driver
- Register the given driver:
Obtain a database connection and return the connection object: method
public static Connection getConnection(String url, String user, String password)url: the connection URL, syntaxjdbc:mysql://ip地址(域名):端口号/数据库名称user: usernamepassword: password
Connection
Connection: the database connection object
Get executor objects
- Get a regular executor:
Statement createStatement() - Get a prepared executor:
PreparedStatement prepareStatement(String sql)
- Get a regular executor:
Transaction management
- Begin a transaction:
setAutoCommit(boolean autoCommit)(false = manual transaction, true = auto‑commit mode, the default) - Commit a transaction:
void commit() - Roll back a transaction:
void rollback()
- Begin a transaction:
Release resources
- Release the database and JDBC resources of this Connection object:
void close()
- Release the database and JDBC resources of this Connection object:
Statement
Statement: object for executing SQL statements
Execute DML statements:
int executeUpdate(String sql)- Returns an
int: the number of rows affected - Parameter
sql: can be anINSERT,UPDATE, orDELETEstatement
- Returns an
Execute DQL statements:
ResultSet executeQuery(String sql)- Returns a
ResultSet: encapsulates the query result - Parameter
sql: can be aSELECTstatement
- Returns a
Release resources
- Release the database and JDBC resources of this Statement object:
void close()
- Release the database and JDBC resources of this Statement object:
ResultSet
ResultSet: result‑set object; it maintains a cursor pointing to the current row, initially positioned before the first row
Check whether the result set contains data:
boolean next()- Returns
trueand moves the cursor down one row if data exists - Returns
falseif no more data
- Returns
Retrieve data from the current row:
XXX getXxx("列名")XXXrepresents the data type (the type of the column you want to fetch)- Example:
String getString("name"); int getInt("age");
Release resources
- Release the database and JDBC resources of this ResultSet object:
void close()
- Release the database and JDBC resources of this ResultSet object:
Code Example
Data preparation
- JDBC connection code:
Injection Attacks
Attack Demonstration
SQL injection demonstration:
- On the login page, entering an incorrect username or password can still result in a successful login.
Mechanism: Everything typed into the password field is treated as part of the password, but the Statement object concatenates part of that input into the SQL query as a condition SELECT * FROM user WHERE loginname='aaa' AND password='aaa' OR '1'='1';.
Mitigation
PreparedStatement: an executor object for pre‑compiled SQL statements, extending Statement.
- Before executing the SQL, the statement is compiled in advance, fixing its structure; the remaining input is treated solely as parameters.
- Parameters in the SQL are represented by
?as placeholders.
Assigning values to the ? placeholder: setXxx(int parameterIndex, xxx data)
- Parameter 1: the position index of
?(indices start at 1) - Parameter 2: the actual value for
?
Executing the SQL:
- For
INSERT,UPDATE,DELETEstatements:int executeUpdate() - For
SELECTstatements: ResultSet executeQuery()
Connection Pools
Concept
Database connections are a critical, limited, and expensive resource—especially in multi‑user web applications. Proper connection management greatly influences an application’s scalability, robustness, and performance metrics.
A database connection pool is responsible for allocating, managing, and releasing connections. It allows an application to reuse an existing connection instead of creating a new one each time, which markedly improves database operation performance.
Returning Connections
Improved via dynamic proxies.
Custom connection‑pool class:
Open‑Source Projects
C3P0 – using the C3P0 connection pool:
Configuration file name:
c3p0-config.xml, must be placed in thesrcdirectoryCode example:
Druid – Druid connection pool:
Configuration file:
druid.properties, must be placed in thesrcdirectoryCode example.
Originally written by Li Wei (李唯_) and published in Chinese on 后端技术栈全书 (Full-Stack Backend Engineering). Translated and adapted for DriftSeas with permission.