Week 103 — How can one connect to a database using JDBC?
Question of the Week #103
How can one connect to a database using JDBC?
3 Replies
JDBC is a database-independent API for access to relational databases. Due to this, applications using JDBC need a database-specific JDBC driver to connect to that database. For example, MySQL Connector/J is used to connect to MySQL databases with JDBC.
The JDBC driver is added to the classpath/modulepath to ensure it being registered or it can also be registered using
DriverManager.registerDriver
.
When a JDBC driver is registered, it is possible to connect to a database supported by the driver using a JDBC connection string identifying the database to connect to. JDBC URLs start with jdbc:
followed by the identifier of the JDBC driver and a driver-specific way to identify the database to connect to as well as possible parameters to the connection. For example, the URL jdbc:mysql://localhost:3306/SomeDatabase
can be used to connect to a MySQL database named SomeDatabase
running on localhost
with the default MySQL port.
The JDBC URL can be passed to the DriverManager.getConnection
together with credentials to the database.
After obtaining a Connection
object, SQL statements can be executed using the Connection#executeUpdate
/Connection#executeQuery
or similar methods:
When including user input in database accesses, it is important to use prepared statements to prevent SQL injections:
📖 Sample answer from dan1st
Steps for DataBase Connectivity with JDBC
Step 1: Register the Driver Class.
Step 2: Create a Connection.
Step 3: Create a Statement.
Step 4: Execute Queries.
Step 5: Close Connection.
Submission from aridorika