Steps for Connecting to MySQL Database in Java: A Complete Guide
#Steps for Connecting MySQL Database in Java: A Complete Guide
Introduction
When building Java applications, connecting to a MySQL database is one of the most common requirements. Java provides JDBC (Java Database Connectivity), an API that enables applications to connect and interact with relational databases such as MySQL.
In this article, you’ll learn the step-by-step process to connect to MySQL in Java, including setup, coding examples, and best practices.
Before connecting Java to MySQL, ensure you have:
Java Development Kit (JDK) installed
MySQL Server installed
MySQL Connector/J (JDBC Driver) downloaded and added to your project classpath
A sample database (e.g., testdb
) with a table (e.g., users
)
Import the required JDBC classes:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
Load the MySQL JDBC Driver:
Class.forName("com.mysql.cj.jdbc.Driver");
Create a connection using DriverManager
:
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
Use the connection object to create a statement:
Statement stmt = con.createStatement();
Execute a query to fetch data from the database:
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
Iterate through the results:
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
Always close the connection to free resources:
con.close();
import java.sql.*;
public class MySQLConnectionDemo {
public static void main(String[] args) {
try {
// Step 1: Load and register JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Establish connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
// Step 3: Create statement
Statement stmt = con.createStatement();
// Step 4: Execute query
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
// Step 5: Process results
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
// Step 6: Close connection
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Output: Displays data from the users
table in the testdb
database.
Always close the connection, statement, and result set.
Use PreparedStatement instead of Statement
to avoid SQL injection.
Store database credentials securely.
Use connection pooling for high-performance applications.
By following these steps, you can easily connect a Java program to a MySQL database using JDBC. Mastering JDBC connections is a key step toward building database-driven Java applications. With best practices like connection pooling and prepared statements, your applications will be secure, scalable, and efficient.
🔑 Target SEO Keywords:
Connect MySQL in Java, JDBC MySQL connection, MySQL Java example, JDBC MySQL tutorial, MySQL database connection steps, JDBC connection in Java, Java MySQL driver.