πŸš€ Complete Guide: Connecting Java to MySQL using JDBC (Step-by-Step with PowerShell + CRUD Operations)


🌟 Introduction

In real-world Java applications, data is stored in databases like MySQL πŸ—„οΈ
To interact with these databases, Java uses JDBC (Java Database Connectivity) πŸ”—

πŸ‘‰ In this blog, you will learn everything from scratch:

  • πŸ“₯ Downloading JDBC driver
  • πŸ“‚ Setting up folder
  • βš™οΈ Using PowerShell / CMD
  • πŸ”— Connecting Java to MySQL
  • 🧾 Performing CRUD operations

🧱 Step 1: Prerequisites


βœ… You must have:

  • Java JDK installed β˜•
  • MySQL running (via phpMyAdmin) πŸ—„οΈ
  • Internet connection 🌐

πŸ“¦ Step 2: Download MySQL Connector/J


πŸ‘‰ Download from official site:

  • MySQL Connector/J (JDBC Driver)

πŸ”Ή Steps:

  1. Open: https://dev.mysql.com/downloads/connector/j/
  2. Select:
    • Platform Independent
  3. Download ZIP file
  4. Click:
    πŸ‘‰ β€œNo thanks, just start my download”

πŸ“‚ Step 3: Extract and Setup Folder


πŸ”Ή Extract ZIP

You will get:

mysql-connector-j-9.x.x.zip

πŸ‘‰ Extract it


πŸ”Ή Create Folder

Create:

C:\jdbc

πŸ”Ή Copy .jar file

Move this file:

mysql-connector-j-9.x.x.jar

πŸ‘‰ Into:

C:\jdbc

βœ… Final Structure

C:\jdbc
β”‚
β”œβ”€β”€ JDBCConnect.java
β”œβ”€β”€ mysql-connector-j-9.x.x.jar

πŸ—„οΈ Step 4: Setup Database (phpMyAdmin)


▢️ Open phpMyAdmin

http://localhost/phpmyadmin

▢️ Create Database

CREATE DATABASE testdb;

▢️ Create Table

USE testdb;

CREATE TABLE student (
    id INT,
    name VARCHAR(50)
);

🧾 Step 5: Write Java Program (Notepad)


Create file:

C:\jdbc\JDBCConnect.java

βœ… Basic Connectivity Program

import java.sql.*;

public class JDBCConnect {
    public static void main(String[] args) {

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/testdb",
                "root",
                ""
            );

            System.out.println("Connected successfully!");

            con.close();

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

βš™οΈ Step 6: Compile & Run (PowerShell)


▢️ Open PowerShell

Windows + R β†’ powershell

▢️ Go to Folder

cd C:\jdbc

▢️ Compile

javac -cp ".;mysql-connector-j-9.6.0.jar" JDBCConnect.java

▢️ Run

java -cp ".;mysql-connector-j-9.6.0.jar" JDBCConnect

πŸŽ‰ Output

Connected successfully!

🧠 Important Concept

πŸ‘‰ In PowerShell:

  • Always use quotes " " with -cp

🧱 Step 7: CRUD Operations (Very Important)


🟒 1. INSERT (Create)

Statement stmt = con.createStatement();

stmt.executeUpdate("INSERT INTO student VALUES (1, 'Ajay')");

πŸ”΅ 2. SELECT (Read)

ResultSet rs = stmt.executeQuery("SELECT * FROM student");

while (rs.next()) {
    System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}

🟑 3. UPDATE

stmt.executeUpdate("UPDATE student SET name='Rahul' WHERE id=1");

πŸ”΄ 4. DELETE

stmt.executeUpdate("DELETE FROM student WHERE id=1");

πŸ§ͺ Complete CRUD Program


import java.sql.*;

public class JDBCCRUD {
    public static void main(String[] args) {

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/testdb",
                "root",
                ""
            );

            Statement stmt = con.createStatement();

            // INSERT
            stmt.executeUpdate("INSERT INTO student VALUES (1, 'Ajay')");

            // UPDATE
            stmt.executeUpdate("UPDATE student SET name='Rahul' WHERE id=1");

            // SELECT
            ResultSet rs = stmt.executeQuery("SELECT * FROM student");

            while (rs.next()) {
                System.out.println(rs.getInt(1) + " " + rs.getString(2));
            }

            // DELETE
            stmt.executeUpdate("DELETE FROM student WHERE id=1");

            con.close();

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

⚠️ Common Errors


❌ Driver not found

πŸ‘‰ Forgot .jar in classpath


❌ Unknown database

πŸ‘‰ Database not created


❌ Access denied

πŸ‘‰ Wrong username/password


❌ Table not found

πŸ‘‰ Table missing in phpMyAdmin


🀯 Common Confusions


πŸ€” Why use .jar file?

πŸ‘‰ It contains JDBC driver


πŸ€” Why -cp needed?

πŸ‘‰ To include external libraries


πŸ’Ό Interview Questions


❓ What is JDBC?

πŸ‘‰ API to connect Java with database


❓ What is Connection?

πŸ‘‰ Represents database connection


❓ Difference between executeQuery & executeUpdate?

πŸ‘‰ SELECT vs INSERT/UPDATE


🎯 Best Practices


βœ”οΈ Always close connection
βœ”οΈ Use PreparedStatement (advanced)
βœ”οΈ Handle exceptions
βœ”οΈ Validate inputs


🏁 Conclusion

Now you can:

  • πŸ”— Connect Java to MySQL
  • βš™οΈ Use PowerShell to run programs
  • 🧾 Perform CRUD operations
  • 🧠 Understand real-world database interaction

πŸ’‘ Final Thought

πŸ‘‰ JDBC is the bridge between Java and databases β€”
πŸ‘‰ mastering it opens doors to real-world development πŸš€


πŸ”₯ One-Line Summary

πŸ‘‰ β€œJDBC connects Java to MySQL using drivers, enabling full database operations.”


πŸ’» Happy Coding! πŸ˜„

You just built your first real database-connected Java program πŸ”₯

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *