Category: java
java with mysql jdbc
Published on 04 Mar 2026
Explanation
First, download the MySQL JDBC driver
(Connector/J). Add
the JAR file to your project's classpath.
Code:
Download MySQL Connector/J from https://dev.mysql.com/downloads/connector/j/
Explanation
Import required JDBC classes to
establish and manage
the database connection.
Code:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;
Explanation
Define database URL, username, and password.
Replace 'testdb'
with your database name.
Code:
String url = "jdbc:mysql://serverurl/db"; String username = "root"; String password = "root";
Explanation
Use DriverManager.getConnection() to
establish connection with MySQL database.
Code:
Connection conn = DriverManager. getConnection(url, username, password);
Explanation
Check if the connection is successful.
Code:
if (conn != null) {
System.out.println("Connect ok");
}
Explanation
Always close the connection after
completing database operations
to avoid memory leaks.
Code:
conn.close();