Hackforge Academy

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();

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community