Introduction to JDBC
JDBC (Java DataBase Connectivity) is a part of the JDK (Java Development Kit) that provides methods to interact with databases.
The api can be found under java.sql and javax.sql.
Connecting to a database
In order to communicate with a database we need to first stablish a connection. The preferred way to get a database connection is using a DataSource
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package example;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
public class JdbcExample {
private static DataSource createDataSource() {
final MysqlDataSource datasource = new MysqlDataSource();
datasource.setPassword("my-secret-pw");
datasource.setUser("root");
datasource.setServerName("0.0.0.0");
return datasource;
}
public static void main(String[] args) throws SQLException {
final Connection con = createDataSource().getConnection();
}
}