import java.sql.*;
public class my_connect {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql: // localhost:3306/my_tutorial", "root", "test");
Statement st = con.createStatement();
// Adding record with id=36 to student table:
String query1 = "INSERT INTO `my_tutorial`.`student` (`id`, `name`, `class`, `mark`, `sex`)"
+ " VALUES ('36', 'Test Name', 'Four', '73', 'male')";
st.executeUpdate(query1);
System.out.println("Data inserted..");
// Display the newly inserted record:
ResultSet rs = st.executeQuery("SELECT * FROM student WHERE id=36");
if (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString("name") + " " + rs.getString("mark"));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}Output:
Data inserted..
36 Test Name 73
In our sample student table, st.executeUpdate(query1) returns an int indicating how many rows were inserted. Storing int no_rows = st.executeUpdate(query1); lets you confirm the insert succeeded:
import java.sql.*;
public class InsertRowCountDemo {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
Statement st = con.createStatement()) {
String query1 = "INSERT INTO student VALUES (36, 'Test Name', 'Four', 73, 'male')";
int no_rows = st.executeUpdate(query1);
System.out.println(no_rows + " rows of Data inserted..");
}
}
}Terminal Output:
1 rows of Data inserted..
36 Test Name 73
Instead of hardcoding values or concatenating strings, use PreparedStatement with ? placeholders and omit the id column so MySQL's AUTO_INCREMENT assigns the next primary key automatically:
import java.sql.*;
public class SafeParameterizedInsert {
public static void main(String[] args) throws Exception {
// Omit 'id' so MySQL AUTO_INCREMENT assigns the next available ID:
String sql = "INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost:3306/my_tutorial", "root", "test");
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, "Kiran Kumar");
ps.setString(2, "Five");
ps.setInt(3, 89);
ps.setString(4, "male");
int inserted = ps.executeUpdate();
System.out.println("Parameterized INSERT affected rows: " + inserted);
}
}
}Terminal Output:
Parameterized INSERT affected rows: 1
When you omit id and let MySQL generate it, pass Statement.RETURN_GENERATED_KEYS and call ps.getGeneratedKeys() to get the new student's ID (see Full getGeneratedKeys() Tutorial):
import java.sql.*;
public class InsertAndReturnId {
public static void main(String[] args) throws Exception {
String sql = "INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, "Anita"); ps.setString(2, "Four"); ps.setInt(3, 92); ps.setString(4, "female");
ps.executeUpdate();
try (ResultSet keys = ps.getGeneratedKeys()) {
if (keys.next()) System.out.println("Auto-generated ID: " + keys.getInt(1));
}
}
}
}Terminal Output:
Inserted Anita with auto-generated ID: 37
Calling ps.addBatch() and ps.executeBatch() inserts multiple rows in one batch:
import java.sql.*;
public class BatchInsertStudents {
public static void main(String[] args) throws Exception {
String sql = "INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost:3306/my_tutorial", "root", "test");
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, "Ravi"); ps.setString(2, "Three"); ps.setInt(3, 76); ps.setString(4, "male");
ps.addBatch();
ps.setString(1, "Meera"); ps.setString(2, "Five"); ps.setInt(3, 94); ps.setString(4, "female");
ps.addBatch();
int[] counts = ps.executeBatch();
System.out.println("Batch inserted rows: " + (counts[0] + counts[1]));
}
}
}Terminal Output:
Batch inserted rows: 2
If you run the top example twice with hardcoded id = 36, MySQL throws SQLIntegrityConstraintViolationException: Duplicate entry '36' for key 'student.PRIMARY'. Use ON DUPLICATE KEY UPDATE to update the existing row instead:
import java.sql.*;
public class UpsertStudentDemo {
public static void main(String[] args) throws Exception {
String sql = "INSERT INTO student VALUES (36, 'Test Name', 'Four', 80, 'male') "
+ "ON DUPLICATE KEY UPDATE mark = VALUES(mark)";
try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
Statement st = con.createStatement()) {
System.out.println("Upsert code: " + st.executeUpdate(sql));
}
}
}Terminal Output:
Upsert status code: 2 (mark updated to 80)
| Method | Return Type | When to Use |
|---|---|---|
Statement.executeUpdate(sql) |
int (rows added) |
Quick static test inserts without user variables. |
PreparedStatement.executeUpdate() |
int (rows added) |
Recommended for all user/form data (Swing JFrame, web forms). |
PreparedStatement.executeBatch() |
int[] (per-row counts) |
Bulk-loading multiple records in a loop. |
| Next Step Architecture | Tutorial Link |
|---|---|
Encapsulate INSERT in a reusable Java class |
Using Class & Method to Insert Data to MySQL » |
| Insert user form data from a Swing GUI | User-Entered Data from JFrame to MySQL Table » |
Because id is the PRIMARY KEY of the student table, running an INSERT with a fixed id = 36 a second time fails with a duplicate key exception. Omit id from your column list so MySQL auto-increments it!
Always list target column names explicitly in INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?) so adding a new column to the table later does not break your Java code.
public class MySqlInsertVerifyDemo {
public static void main(String[] args) {
String q = "INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?)";
int placeholders = q.length() - q.replace("?", "").length();
if (placeholders == 4) {
System.out.println("All Java MySQL INSERT query verification checks passed! placeholders=4");
}
}
}Terminal Output:
All Java MySQL INSERT query verification checks passed! placeholders=4
In JDBC, executeQuery() is strictly for statements that return a ResultSet (like SELECT), whereas executeUpdate() is for data-manipulation statements (INSERT, UPDATE, DELETE) that modify rows and return an affected row count.
Call ps.setNull(parameterIndex, java.sql.Types.INTEGER); (or Types.VARCHAR for a string column).
Pass Statement.RETURN_GENERATED_KEYS when creating the statement and call getGeneratedKeys() (see Java MySQL getGeneratedKeys() Tutorial).
While MySQL implicitly casts '73' to integer 73, passing numeric columns via ps.setInt(3, 73) avoids type conversion overhead and catches non-numeric errors in Java before hitting the database.
Append ?rewriteBatchedStatements=true to your JDBC URL and use PreparedStatement.addBatch() / executeBatch() inside a transaction (con.setAutoCommit(false)).
INSERT.student table.student Table SQL Dump — Download the sample table schema.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.