Establishing a connection to a database is the first major step in JDBC programming. It allows a Java application to communicate with a database and perform operations such as executing SQL queries, inserting records, updating data, and retrieving results. JDBC provides the Connection interface and DriverManager class to establish and manage database connections. A connection requires the database URL, username, and password. Once the required operations are completed, the connection should be properly closed to release database resources.
Program: Establishing a Connection to a Database
This program establishes a connection between a Java application and a MySQL database using JDBC. It uses DriverManager.getConnection() with the database URL, username, and password. After establishing the connection, the program checks whether the connection is successful and then closes it.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnectionExample {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/jdbc_demo";
String username = "root";
String password = "password";
try {
// Establish connection
Connection con =
DriverManager.getConnection(
url, username, password);
// Check connection
if (con != null) {
System.out.println(
"Database connection established successfully.");
System.out.println(
"Connection Status: " +
!con.isClosed());
}
// Close connection
con.close();
System.out.println(
"Database connection closed.");
} catch (SQLException e) {
System.out.println(
"Database connection failed.");
System.out.println(
"Error: " + e.getMessage());
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\mysql-connector.jar" DatabaseConnectionExample.java
PS D:\test> java -classpath ".;D:\test\mysql-connector.jar" DatabaseConnectionExample
Database connection established successfully.
Connection Status: true
Database connection closed.Code language: JavaScript (javascript)
