Java Notes
Step-by-step guide to connecting Java with MySQL — driver setup, connection URLs, properties, SSL configuration, and troubleshooting common errors.
Prerequisites
- MySQL Server installed and running (MySQL 8.0+)
- MySQL Connector/J (JDBC driver for MySQL)
- Java 8+ installed
Install MySQL (if needed)
# Ubuntu/Debian
sudo apt install mysql-server
# macOS (Homebrew)
brew install mysql
# Windows - download from mysql.com or use XAMPP
# Start MySQL
sudo systemctl start mysql # Linux
brew services start mysql # macOS
# Log in and create database
mysql -u root -p-- Create database and user
CREATE DATABASE IF NOT EXISTS java_course;
CREATE USER IF NOT EXISTS 'javauser'@'localhost' IDENTIFIED BY 'JavaPass123!';
GRANT ALL PRIVILEGES ON java_course.* TO 'javauser'@'localhost';
FLUSH PRIVILEGES;
-- Create tables
USE java_course;
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
department VARCHAR(50),
salary DECIMAL(10, 2),
hire_date DATE,
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO employees (first_name, last_name, email, department, salary, hire_date) VALUES
('John', 'Doe', 'john.doe@company.com', 'Engineering', 85000.00, '2020-03-15'),
('Jane', 'Smith', 'jane.smith@company.com', 'Marketing', 72000.00, '2019-07-22'),
('Bob', 'Johnson', 'bob.johnson@company.com', 'Engineering', 92000.00, '2018-01-10'),
('Alice', 'Williams', 'alice.w@company.com', 'HR', 68000.00, '2021-09-01'),
('Charlie', 'Brown', 'charlie.b@company.com', 'Engineering', 78000.00, '2022-02-14');Connection Methods
Method 1: Basic DriverManager
import java.sql.*;
public class BasicConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/java_course";
String user = "javauser";
String password = "JavaPass123!";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("✅ Connected successfully!");
System.out.println("Database: " + conn.getCatalog());
System.out.println("Schema: " + conn.getSchema());
// Test with a query
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM employees")) {
if (rs.next()) {
System.out.println("Employee count: " + rs.getInt(1));
}
}
} catch (SQLException e) {
System.err.println("Connection failed!");
System.err.println("Message: " + e.getMessage());
System.err.println("SQL State: " + e.getSQLState());
System.err.println("Error Code: " + e.getErrorCode());
}
}
}✅ Connected successfully!
Method 2: With Connection Properties
import java.sql.*;
import java.util.Properties;
public class PropertiesConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/java_course";
Properties props = new Properties();
props.setProperty("user", "javauser");
props.setProperty("password", "JavaPass123!");
props.setProperty("useSSL", "false");
props.setProperty("serverTimezone", "UTC");
props.setProperty("characterEncoding", "UTF-8");
props.setProperty("connectTimeout", "5000");
props.setProperty("socketTimeout", "30000");
props.setProperty("autoReconnect", "true");
try (Connection conn = DriverManager.getConnection(url, props)) {
System.out.println("✅ Connected with properties!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}✅ Connected with properties!
Method 3: URL with Parameters
String url = "jdbc:mysql://localhost:3306/java_course" +
"?useSSL=false" +
"&serverTimezone=UTC" +
"&characterEncoding=UTF-8" +
"&useUnicode=true" +
"&rewriteBatchedStatements=true" +
"&cachePrepStmts=true" +
"&prepStmtCacheSize=250" +
"&prepStmtCacheSqlLimit=2048";
Connection conn = DriverManager.getConnection(url, "javauser", "JavaPass123!");Method 4: Production-Ready Configuration File
// db.properties file
/*
db.url=jdbc:mysql://localhost:3306/java_course
db.user=javauser
db.password=JavaPass123!
db.driver=com.mysql.cj.jdbc.Driver
db.pool.size=10
*/
import java.io.InputStream;
import java.util.Properties;
public class ConfigFileConnection {
private static Properties dbProps = new Properties();
static {
try (InputStream is = ConfigFileConnection.class
.getClassLoader().getResourceAsStream("db.properties")) {
dbProps.load(is);
Class.forName(dbProps.getProperty("db.driver"));
} catch (Exception e) {
throw new RuntimeException("Failed to load DB config", e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(
dbProps.getProperty("db.url"),
dbProps.getProperty("db.user"),
dbProps.getProperty("db.password")
);
}
}Complete CRUD Example
import java.sql.*;
public class EmployeeCRUD {
private static final String URL = "jdbc:mysql://localhost:3306/java_course?useSSL=false&serverTimezone=UTC";
private static final String USER = "javauser";
private static final String PASSWORD = "JavaPass123!";
// CREATE
public static int createEmployee(String firstName, String lastName,
String email, String dept, double salary) {
String sql = "INSERT INTO employees (first_name, last_name, email, department, salary, hire_date) " +
"VALUES (?, ?, ?, ?, ?, CURDATE())";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
pstmt.setString(1, firstName);
pstmt.setString(2, lastName);
pstmt.setString(3, email);
pstmt.setString(4, dept);
pstmt.setDouble(5, salary);
int affected = pstmt.executeUpdate();
if (affected > 0) {
try (ResultSet keys = pstmt.getGeneratedKeys()) {
if (keys.next()) {
int id = keys.getInt(1);
System.out.println("Created employee with ID: " + id);
return id;
}
}
}
} catch (SQLException e) {
System.err.println("Create failed: " + e.getMessage());
}
return -1;
}
// READ (single)
public static void getEmployee(int id) {
String sql = "SELECT * FROM employees WHERE id = ?";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
System.out.printf("ID: %d | Name: %s %s | Email: %s | Dept: %s | Salary: $%.2f%n",
rs.getInt("id"),
rs.getString("first_name"),
rs.getString("last_name"),
rs.getString("email"),
rs.getString("department"),
rs.getDouble("salary"));
} else {
System.out.println("Employee not found: " + id);
}
}
} catch (SQLException e) {
System.err.println("Read failed: " + e.getMessage());
}
}
// READ (all)
public static void getAllEmployees() {
String sql = "SELECT * FROM employees WHERE is_active = TRUE ORDER BY last_name";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
System.out.println("\n=== All Active Employees ===");
System.out.printf("%-4s %-15s %-15s %-12s %10s%n",
"ID", "First Name", "Last Name", "Department", "Salary");
System.out.println("-".repeat(60));
while (rs.next()) {
System.out.printf("%-4d %-15s %-15s %-12s $%,10.2f%n",
rs.getInt("id"),
rs.getString("first_name"),
rs.getString("last_name"),
rs.getString("department"),
rs.getDouble("salary"));
}
} catch (SQLException e) {
System.err.println("Read all failed: " + e.getMessage());
}
}
// UPDATE
public static boolean updateSalary(int id, double newSalary) {
String sql = "UPDATE employees SET salary = ? WHERE id = ? AND is_active = TRUE";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setDouble(1, newSalary);
pstmt.setInt(2, id);
int affected = pstmt.executeUpdate();
if (affected > 0) {
System.out.println("Salary updated for employee " + id);
return true;
} else {
System.out.println("No employee found/updated for ID: " + id);
}
} catch (SQLException e) {
System.err.println("Update failed: " + e.getMessage());
}
return false;
}
// DELETE (soft delete)
public static boolean deleteEmployee(int id) {
String sql = "UPDATE employees SET is_active = FALSE WHERE id = ?";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
int affected = pstmt.executeUpdate();
System.out.println(affected > 0 ? "Employee deactivated" : "Employee not found");
return affected > 0;
} catch (SQLException e) {
System.err.println("Delete failed: " + e.getMessage());
}
return false;
}
public static void main(String[] args) {
// Test CRUD operations
getAllEmployees();
int newId = createEmployee("David", "Wilson", "david.w@company.com", "Finance", 75000.00);
getEmployee(newId);
updateSalary(newId, 80000.00);
getEmployee(newId);
deleteEmployee(newId);
getAllEmployees();
}
}\n=== All Active Employees ===
Troubleshooting Common Errors
| Error | Cause | Fix |
|---|---|---|
Communications link failure | MySQL not running or wrong host/port | Start MySQL, check URL |
Access denied for user | Wrong username/password | Verify credentials |
Unknown database | Database doesn't exist | CREATE DATABASE first |
No suitable driver found | Driver not in classpath | Add MySQL connector JAR |
SSL connection error | SSL required but not configured | Add ?useSSL=false for dev |
Public Key Retrieval not allowed | Auth plugin issue | Add &allowPublicKeyRetrieval=true |
The server time zone value | Timezone mismatch | Add &serverTimezone=UTC |
Interview Questions
Q1: What JDBC URL format does MySQL use?
Answer: jdbc:mysql://hostname:port/database?param1=value1¶m2=value2. Default port is 3306.
Q2: Why use PreparedStatement instead of Statement for CRUD?
Answer: PreparedStatement prevents SQL injection, enables query plan caching, handles data type conversion, and supports binary data. Statement with string concatenation is a critical security vulnerability.
Q3: What is the purpose of try-with-resources in JDBC?
Answer: Automatically closes Connection, Statement, and ResultSet when the block exits (even on exceptions), preventing resource leaks that exhaust the connection pool.
Q4: How do you get the auto-generated ID after an INSERT?
Answer: Pass Statement.RETURN_GENERATED_KEYS to prepareStatement(), then call pstmt.getGeneratedKeys() after executeUpdate() to get a ResultSet with the generated key.
Q5: What is the difference between executeQuery, executeUpdate, and execute?
Answer: executeQuery() — for SELECT, returns ResultSet. executeUpdate() — for INSERT/UPDATE/DELETE, returns affected row count. execute() — for any SQL, returns boolean (true=ResultSet, false=update count).
Summary
In this chapter, we learned about MySQL Connection with JDBC in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for MySQL Connection with JDBC.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, jdbc, mysql, connection
Related Java Master Course Topics