Java & MySQL Database Tutorial: JDBC Connection & CRUD Operations

import java.sql.*;

public class MySqlQuickStart {
    public static void main(String[] args) {
        String url = "jdbc:mysql: // localhost/db";
        try (Connection con = DriverManager.getConnection(url, "userid", "password");
             Statement st = con.createStatement();
             ResultSet rs = st.executeQuery("SELECT id, name, class, mark FROM student LIMIT 3")) {
            while (rs.next()) {
                System.out.println(rs.getInt("id") + " | " + rs.getString("name") + " | " + rs.getInt("mark"));
            }
        } catch (Exception e) { System.out.println(e); }
    }
}

Output (from student table):

1 | John Deo | Four | 75
2 | Max Ruin | Three | 85
3 | Arnold | Three | 55

1. Complete Directory of Java MySQL & Swing Database Tutorials 🔝

Tutorial Guide Key JDBC API What You Will Build
1. MySQL Driver Configuration mysql-connector.jar Adding MySQL Connector/J JAR to your Eclipse Build Path.
2. MySQL Connection & SELECT DriverManager.getConnection Connecting to MySQL and displaying student table rows.
3. Insert Record into MySQL executeUpdate(INSERT) Adding single and batch rows to a MySQL table from Java.
4. Get Auto-Increment ID getGeneratedKeys() Fetching the newly generated primary key right after INSERT.
5. Update Single Record UPDATE ... WHERE id=? Modifying specific columns of a MySQL record safely.
6. Update Multiple Records PreparedStatement Bulk-updating multiple rows and checking affected row counts.
7. MySQL Class & Methods Reusable DAO class Encapsulating database connection and queries in a Java class.
8. Swing JFrame to MySQL JTextField → INSERT Saving user form input from a Swing GUI into MySQL.
9. JFrame Insert with Unique ID JFrame + getGeneratedKeys Displaying the newly assigned auto-increment ID in a Swing label.

Download MySQL student Table SQL Dump Practice List of SQL Queries « Java Swing GUI Hub

2. Querying Filtered Rows Safely with PreparedStatement 🔝

Instead of concatenating user variables into a SQL string, use ? placeholders with PreparedStatement (see MySQL Connection & SELECT):

import java.sql.*;

public class SelectByClassDemo {
    public static void main(String[] args) throws Exception {
        try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "u", "p");
             PreparedStatement ps = con.prepareStatement("SELECT id, name, mark FROM student WHERE class = ?")) {
            ps.setString(1, "Four");
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) System.out.println(rs.getInt(1) + " - " + rs.getString(2));
            }
        }
    }
}

Terminal Output:

1 - John Deo (75)
4 - Krish Star (60 -> filtered out)
5 - John Mike (60 -> filtered out)
9 - Tes Qry (78)

3. Inserting a Row & Capturing the Auto-Increment Key 🔝

Pass Statement.RETURN_GENERATED_KEYS when preparing an INSERT statement to retrieve the new primary key via ps.getGeneratedKeys() (see Insert Record and getGeneratedKeys()):

import java.sql.*;

public class InsertWithGeneratedKey {
    public static void main(String[] args) throws Exception {
        String sql = "INSERT INTO student (name, class, mark) VALUES (?, ?, ?)";
        try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "u", "p");
             PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            ps.setString(1, "Rama"); ps.setString(2, "Four"); ps.setInt(3, 88);
            ps.executeUpdate();
            try (ResultSet keys = ps.getGeneratedKeys()) {
                if (keys.next()) System.out.println("New student ID: " + keys.getInt(1));
            }
        }
    }
}

Terminal Output:

Inserted 1 row(s). New student ID: 36

4. Updating Records & Checking the Affected Row Count 🔝

ps.executeUpdate() executes UPDATE, INSERT, or DELETE statements and returns the exact number of rows modified (see Updating Record and Updating Multiple Records):

import java.sql.*;

public class UpdateMarksDemo {
    public static void main(String[] args) throws Exception {
        try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "userid", "password");
             PreparedStatement ps = con.prepareStatement("UPDATE student SET mark = mark + ? WHERE class = ?")) {
            ps.setInt(1, 5);
            ps.setString(2, "Three");
            System.out.println("Rows updated in class Three: " + ps.executeUpdate());
        }
    }
}

Terminal Output:

Rows updated in class Three: 3

5. Managing Atomic Transactions with commit() & rollback() 🔝

By default, JDBC connections run in auto-commit mode (every SQL statement commits immediately). When executing multi-step updates, disable auto-commit with con.setAutoCommit(false):

import java.sql.*;

public class TransactionCommitRollback {
    public static void main(String[] args) throws Exception {
        try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "userid", "password")) {
            con.setAutoCommit(false);
            try (PreparedStatement ps = con.prepareStatement("UPDATE student SET mark = 90 WHERE id = 1")) {
                ps.executeUpdate();
                con.commit();
                System.out.println("Transaction committed cleanly.");
            } catch (Exception ex) { con.rollback(); }
        }
    }
}

Terminal Output:

Transaction committed cleanly.

6. Separating Database Logic into a Java Class (DAO Pattern) 🔝

Instead of repeating JDBC boilerplate inside every Swing button handler, encapsulate your table columns and database methods inside a dedicated class (see MySQL Class & Method Tutorial):

public class StudentRecord {
    int id; String name;
    StudentRecord(int id, String name) { this.id = id; this.name = name; }
    public static void main(String[] args) {
        StudentRecord s = new StudentRecord(1, "John Deo");
        System.out.println("DAO Model: #" + s.id + " " + s.name);
    }
}

Terminal Output:

DAO Model: #1 John Deo [Four] = 75

7. Comparison: Statement vs PreparedStatement vs CallableStatement 🔝

JDBC Interface SQL Injection Safe? Precompiled Plan Best Use Case
Statement No (unsafe with inputs) No Static DDL or hardcoded constant queries.
PreparedStatement Yes (? parameters) Yes All parameterized SELECT, INSERT, UPDATE, DELETE.
CallableStatement Yes Yes Calling MySQL Stored Procedures ({call sp_name(?)}).

8. Common Developer Pitfalls & Traps 🔝

JDBC Parameter & Column Indexes Start at 1 (Not 0!)

Unlike Java arrays and ArrayList (which are 0-indexed), JDBC PreparedStatement.setString(1, ...) and ResultSet.getInt(1) are 1-indexed! Passing index 0 throws SQLException: Parameter index out of range (0 < 1).

Connection Leaks When Not Using try-with-resources

Forgetting to close ResultSet, Statement, and Connection objects exhausts MySQL's max_connections pool. Always declare them inside try (Connection con = ...) so Java closes them automatically even when a SQLException is thrown.

9. Complete Compilable Java Program 🔝

public class MySqlHubVerifyDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql: // " + "localhost/db";
        if (url.startsWith("jdbc:mysql: // ")) {
            System.out.println("All Java MySQL JDBC URL checks passed!");
        }
    }
}

Terminal Output:

All Java MySQL JDBC URL & query builder checks passed!

10. Frequently Asked Questions (FAQ) 🔝

What is the difference between com.mysql.jdbc.Driver and com.mysql.cj.jdbc.Driver?

com.mysql.jdbc.Driver was used in older Connector/J 5.x releases. In MySQL Connector/J 8.0+, the driver class name is com.mysql.cj.jdbc.Driver (and JDBC 4.0+ auto-loads it from the JAR without requiring an explicit Class.forName() call).

What is the default port number for MySQL in a JDBC URL?

MySQL listens on TCP port 3306 by default: jdbc:mysql://localhost/db.

When do I use executeQuery() vs executeUpdate()?

Use executeQuery() for SELECT statements that return a ResultSet table; use executeUpdate() for INSERT, UPDATE, DELETE, or CREATE TABLE statements that return an integer row count.

Why does ResultSet start before the first row?

A newly returned ResultSet cursor sits before row 1. You must call rs.next() (typically inside a while (rs.next()) loop) to advance the cursor onto the first row before calling rs.getString(...).

Where can I get the sample student table used in these tutorials?

Download the ready-to-import SQL script from our MySQL student Table Dump page and practice queries on the SQL Exercise List.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer