Java Program to Connect to Database
using JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCConnectionExample {
public static void main(String[] args) {
// Database URL, username, and password
String jdbcURL = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "your_password"; // change this to your actual
password
Connection connection = null;
try {
// Load MySQL JDBC driver (optional in modern Java, but good
practice)
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to the database
connection = DriverManager.getConnection(jdbcURL, username,
password);
System.out.println("Connection successful!");
} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Connection failed. Check output
console.");
e.printStackTrace();
} finally {
// Close the connection
try {
if (connection != null && !connection.isClosed()) {
connection.close();
System.out.println("Connection closed.");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
Output:
Connection successful!
Connection closed.