MySQL Database Connection - Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLConnection {
// Connection parameters
private static final String URL = "jdbc:mysql://localhost:3306/school_db";
private static final String USER = "root";
private static final String PASSWORD = "password";
public static Connection connect() {
"""Connect to MySQL database with error handling"""
Connection connection = null;
try {
// Load MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection
connection = DriverManager.getConnection(URL, USER, PASSWORD);
System.out.println("β
Connected to MySQL database successfully");
} catch (ClassNotFoundException e) {
System.err.println("β MySQL JDBC Driver not found: " + e.getMessage());
} catch (SQLException e) {
System.err.println("β Connection failed: " + e.getMessage());
}
return connection;
}
public static boolean testConnection(Connection connection) {
"""Test if connection is active"""
if (connection != null) {
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT DATABASE()");
if (resultSet.next()) {
String dbName = resultSet.getString(1);
System.out.println("π Current database: " + dbName);
}
resultSet.close();
statement.close();
return true;
} catch (SQLException e) {
System.err.println("β Error testing connection: " + e.getMessage());
}
}
return false;
}
public static void closeConnection(Connection connection) {
"""Safely close database connection"""
if (connection != null) {
try {
connection.close();
System.out.println("π MySQL connection closed");
} catch (SQLException e) {
System.err.println("β Error closing connection: " + e.getMessage());
}
}
}
public static void main(String[] args) {
// Connect to database
Connection conn = connect();
if (conn != null) {
// Test connection
testConnection(conn);
// Your database operations here
// Close connection
closeConnection(conn);
}
}
}
π οΈ Connection Parameters
| Parameter |
Example |
Description |
URL |
jdbc:mysql://localhost:3306/school_db |
JDBC connection string |
USER |
root |
MySQL username |
PASSWORD |
password |
MySQL password |
DRIVER |
com.mysql.cj.jdbc.Driver |
MySQL JDBC driver class |
π§ Connection String Variations
With SSL Configuration
private static final String URL =
"jdbc:mysql://localhost:3306/school_db?useSSL=false&serverTimezone=UTC";
Remote Database
private static final String URL =
"jdbc:mysql://your-server.com:3306/production_db?useSSL=true";
With Connection Pool
// Using HikariCP connection pool
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/school_db");
config.setUsername("root");
config.setPassword("password");
HikariDataSource dataSource = new HikariDataSource(config);
Connection connection = dataSource.getConnection();
β οΈ Common Errors & Solutions
| Exception |
Cause |
Solution |
ClassNotFoundException |
MySQL driver not in classpath |
Add MySQL connector JAR |
SQLException: Access denied |
Wrong credentials |
Check username/password |
SQLException: Unknown database |
Database doesn't exist |
Create database first |
CommunicationsException |
Server not running/port blocked |
Start MySQL, check firewall |
π Dependencies (Maven)
<dependencies>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- Connection Pool (Optional) -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>5.0.1</version>
</dependency>
</dependencies>
π Dependencies (Gradle)
dependencies {
// MySQL Connector
implementation 'mysql:mysql-connector-java:8.0.33'
// Connection Pool (Optional)
implementation 'com.zaxxer:HikariCP:5.0.1'
}
π Learn Database Theory β