Getting started with jdbc
Remarks#
JDBC, or Java DataBase Connectivity, is the Java specification for connecting to (relational) databases. JDBC provides a common API in the form of a number of interfaces and exceptions, and expectations (or requirements) of drivers.
The JDBC specification consists of two parts:
- A specification document, available from the JSR-221 page
- The API and its documentation, included with the Java SE API (packages
java.sql
andjavax.sql
)
Most relational databases, and some non-relational databases, provide a driver that implements the JDBC.
Versions#
Version | Release Date |
---|---|
3.0 | 2002-02-06 |
4.0 | 2006-12-11 |
4.1 | 2011-07-07 |
4.2 | 2014-03-18 |
Creating a connection
To be able to use JDBC you need to have the JDBC driver of your database on the class path of your application.
There are multiple ways to connect to a database, but the common ways are to either use the java.sql.DriverManager
, or to configure and use a database specific implementation of javax.sql.DataSource
.
A simple example to create a connection to a database with the url jdbc:somedb://localhost/foobar
and execute an update statement to give all employees a 5% raise:
try (Connection connection = DriverManager.getConnection(
"jdbc:somedb://localhost/foobar", "anna", "supersecretpassword");
Statement updateStatement = connection.createStatement()) {
updateStatement.executeUpdate("update employees set salary = salary * 1.05");
}
For further details see creating a database connection