Java Program to Connect to Database
using JDBC
import [Link];
import [Link];
import [Link];
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)
[Link]("[Link]");
// Connect to the database
connection = [Link](jdbcURL, username,
password);
[Link]("Connection successful!");
} catch (ClassNotFoundException e) {
[Link]("MySQL JDBC Driver not found.");
[Link]();
} catch (SQLException e) {
[Link]("Connection failed. Check output
console.");
[Link]();
} finally {
// Close the connection
try {
if (connection != null && ![Link]()) {
[Link]();
[Link]("Connection closed.");
}
} catch (SQLException ex) {
[Link]();
}
}
}
}
Output:
Connection successful!
Connection closed.