Adding Records to a MySQL Table from Java Eclipse

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

1. Capturing the Number of Records Added with executeUpdate() 🔝

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

2. Production Best Practice: Parameterized PreparedStatement INSERT 🔝

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

3. Retrieving the Auto-Increment Key After INSERT 🔝

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

4. Inserting Multiple Rows Efficiently with addBatch() & executeBatch() 🔝

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

5. Avoiding Duplicate Key Errors with ON DUPLICATE KEY UPDATE 🔝

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)

6. Comparison of Java JDBC INSERT Approaches 🔝

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 »

7. Common Developer Pitfalls & Traps 🔝

Duplicate entry '36' for key 'PRIMARY' on Second Run

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!

Column Count Doesn't Match Value Count at Row 1

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.

8. Complete Compilable Java Program 🔝

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

9. Frequently Asked Questions (FAQ) 🔝

Why do we use executeUpdate() instead of executeQuery() for INSERT?

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.

How do I insert a NULL value into a column using PreparedStatement?

Call ps.setNull(parameterIndex, java.sql.Types.INTEGER); (or Types.VARCHAR for a string column).

How do I get the auto-increment ID of the row I just inserted?

Pass Statement.RETURN_GENERATED_KEYS when creating the statement and call getGeneratedKeys() (see Java MySQL getGeneratedKeys() Tutorial).

Why should numeric columns like id and mark be passed without single quotes?

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.

How can I speed up bulk inserts of 10,000+ rows in MySQL Connector/J?

Append ?rewriteBatchedStatements=true to your JDBC URL and use PreparedStatement.addBatch() / executeBatch() inside a transaction (con.setAutoCommit(false)).

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