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
| 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
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)
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
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
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.
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
| 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(?)}). |
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).
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.
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!
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).
MySQL listens on TCP port 3306 by default: jdbc:mysql://localhost/db.
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.
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(...).
Download the ready-to-import SQL script from our MySQL student Table Dump page and practice queries on the SQL Exercise List.
ResultSet.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.