← Back to Chapters

Java MySQL Connection

☕ Java MySQL Connection (JDBC)

? Quick Overview

Java Database Connectivity (JDBC) is an API that allows Java applications to connect and interact with databases. Using JDBC, Java programs can connect to MySQL, execute SQL queries, and process results efficiently.

? Key Concepts

  • JDBC Driver – Enables Java to communicate with MySQL
  • Connection – Represents a database session
  • Statement – Executes SQL queries
  • ResultSet – Stores query results

? Interactive Connection Simulator

Click the button below to visualize how Java connects to the Database.

Java App
 
? Driver
 
? MySQL DB
Ready to connect...

? Syntax / Theory

To connect Java with MySQL, the JDBC driver must be loaded, a connection URL must be provided, and valid database credentials are required.

? Code Example

? View Code Example
// Import JDBC classes
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class MySQLConnectionDemo {
public static void main(String[] args) {
try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Create connection to MySQL database
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);

// Create statement object
Statement stmt = con.createStatement();

// Connection successful message
System.out.println("Connected to MySQL database successfully");

con.close();
} catch (Exception e) {
// Handle any errors
e.printStackTrace();
}
}
}

? Live Output / Explanation

Expected Output

When the program runs successfully, it prints:

Connected to MySQL database successfully

This confirms that Java has successfully established a connection with the MySQL database.

✅ Tips & Best Practices

  • Always close database connections after use
  • Use PreparedStatement for secure queries
  • Keep database credentials secure
  • Use try-with-resources when possible

? Try It Yourself

  • Change database name and credentials
  • Execute a SELECT query using ResultSet
  • Create a table using JDBC
  • Insert records into MySQL from Java