Database Connection with Java JDBC
Java JDBC (Java Database Connectivity) is an API that allows Java applications to connect to databases. JDBC enables applications written in Java to make database queries and interact with the database. In this article, we will examine step by step how we can establish a database connection with Java JDBC.
Overview of JDBC
Java JDBC acts as a bridge between Java applications and relational databases. JDBC offers many methods to send and receive SQL queries and does this by using database drivers. The operation is carried out using the appropriate JDBC drivers depending on which database the user is working with.
JDBC Drivers
JDBC offers various drivers to interact with different databases. The most common types of drivers are:
- Type 1: JDBC-ODBC Bridge
- Type 2: Native API
- Type 3: Network Protocol Driver
- Type 4: Thin Driver
Establishing a Database Connection
You can follow the steps below to establish a database connection with JDBC. Below is an example of connecting to a MySQL database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
public static void main(String[] args) {
Connection connection = null;
String url = "jdbc:mysql://localhost:3306/database_name";
String user = "username";
String password = "password";
try {
connection = DriverManager.getConnection(url, user, password);
if (connection != null) {
System.out.println("Database connection established successfully.");
}
} catch (SQLException e) {
System.out.println("An error occurred during the database connection: " + e.getMessage());
} finally {
try {
if (connection != null) connection.close();
} catch (SQLException ex) {
System.out.println("An error occurred while closing the connection: " + ex.getMessage());
}
}
}
}
Conclusion
Establishing a database connection with Java JDBC is quite simple. JDBC allows you to interact with databases quickly and effectively. In this article, you learned how to connect to a MySQL database with JDBC. You can seamlessly perform database operations in your applications using JDBC.

Yorum Gönder