Java CRUD Operations using MySQL For Beginners

Updated

MariaDB and MySQL database servers

Two things decide whether Java CRUD against MySQL works: the right connector artifact on the classpath, and parameters instead of string concatenation. The artifact is com.mysql:mysql-connector-j — the old mysql:mysql-connector-java is dead, and its last release on Maven Central is 8.0.33, published 2023-04-14. Use:

<dependency>
  <groupId>com.mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
  <version>26.7.0</version>
</dependency>

You do not need Class.forName(...). The jar ships META-INF/services/java.sql.Driver containing exactly one line — com.mysql.cj.jdbc.Driver — and DriverManager finds it through the service loader. Printing the registered drivers before touching Class.forName at all:

drivers registered before any Class.forName:
  com.mysql.cj.jdbc.Driver 26.7

If you copy an older tutorial and load the pre-8.0 class name, the driver tells you itself:

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

Fixing “cannot find symbol” for DriverManager

Code that imports Connection, PreparedStatement and SQLException but uses DriverManager without importing it does not compile. javac 26.0.2 reports:

CreateUser.java:7: error: cannot find symbol
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/SampleDB", "root", "password");
                                     ^
  symbol:   variable DriverManager
  location: class CreateUser
1 error

Add import java.sql.DriverManager;, or just import java.sql.*;. Relying on a download page and an Eclipse “Add External JARs” dialog instead of naming the artifact is exactly how people end up on 8.0.33 in 2026.

All four operations, one file

This compiles and runs as written. Credentials come from the environment; hardcoding "root", "password" into every example is how they end up in version control. If your own MySQL 8.x server accepts mysql -u root, mysql-crud-operations-example.sh downloads Connector/J 26.7.0 and repeats this page’s checks — the missing-import error, the driver registration, the four operations and the injection tests; it drops the account it creates but leaves the emptied hw_jcrud_v schema behind and prints the DROP DATABASE command for it.

import java.sql.*;

public class Crud {
    static final String URL  = System.getenv("DB_URL");
    static final String USER = System.getenv("DB_USER");
    static final String PASS = System.getenv("DB_PASSWORD");

    public static void main(String[] args) throws SQLException {
        try (Connection c = DriverManager.getConnection(URL, USER, PASS)) {
            int id = create(c, "John Doe", "john.doe@example.com");
            System.out.println("CREATE  -> generated id " + id);
            read(c);
            System.out.println("UPDATE  -> rows " + update(c, id, "Jane Doe", "jane.doe@example.com"));
            System.out.println("DELETE  -> rows " + delete(c, id));
        }
    }

    static int create(Connection c, String name, String email) throws SQLException {
        String sql = "INSERT INTO hw_users (name, email) VALUES (?, ?)";
        try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            ps.setString(1, name);
            ps.setString(2, email);
            ps.executeUpdate();
            try (ResultSet keys = ps.getGeneratedKeys()) {
                return keys.next() ? keys.getInt(1) : -1;
            }
        }
    }

    static void read(Connection c) throws SQLException {
        try (PreparedStatement ps = c.prepareStatement(
                 "SELECT id, name, email, created_at FROM hw_users ORDER BY id");
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                System.out.printf("  row id=%d name=%s email=%s created_at=%s%n",
                    rs.getInt("id"), rs.getString("name"),
                    rs.getString("email"), rs.getTimestamp("created_at"));
            }
        }
    }

    static int update(Connection c, int id, String name, String email) throws SQLException {
        try (PreparedStatement ps = c.prepareStatement(
                 "UPDATE hw_users SET name = ?, email = ? WHERE id = ?")) {
            ps.setString(1, name); ps.setString(2, email); ps.setInt(3, id);
            return ps.executeUpdate();
        }
    }

    static int delete(Connection c, int id) throws SQLException {
        try (PreparedStatement ps = c.prepareStatement("DELETE FROM hw_users WHERE id = ?")) {
            ps.setInt(1, id);
            return ps.executeUpdate();
        }
    }
}

Compiled with javac -cp mysql-connector-j-26.7.0.jar Crud.java and run against a live server, it prints:

driver: MySQL Connector/J mysql-connector-j-26.7.0 (Revision: 559f62df01d4f618440da174ff45ba87f7b3b2a8)
server: 8.4.10
CREATE  -> generated id 1
  row id=1 name=John Doe email=john.doe@example.com created_at=2026-08-10 13:11:55.0
UPDATE  -> rows 1
  row id=1 name=Jane Doe email=jane.doe@example.com created_at=2026-08-10 13:11:55.0
DELETE  -> rows 1
READ    -> rows remaining 0

Statement.RETURN_GENERATED_KEYS plus getGeneratedKeys() is how you get the auto-increment id back. Leaving it out pushes people toward SELECT MAX(id) — a race waiting to happen under concurrency.

Why the placeholders matter, measured

Use PreparedStatement. Here is what it buys you. Against a table holding three rows, with the input x' OR '1'='1:

concatenated SQL: SELECT id, name FROM hw_users WHERE email = 'x' OR '1'='1'
  rows returned:  3
prepared, same input
  rows returned:  0

Concatenation turned a lookup for one address into a dump of the table. The prepared version sent the same characters as a value and matched nothing, which is the correct answer. Note the placeholder must be the value itself — prepareStatement("... WHERE email = '" + x + "'") is still concatenation, and so is any query where a column or table name comes from input. Identifiers cannot be bound; check those against an allowlist.

One thing worth knowing before you panic about a specific payload: Connector/J does not allow stacked statements by default. The classic ; DROP TABLE ending fails at the parser:

stacked query blocked: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELETE FROM hw_users WHERE 1=1' at line 1
rows still in table: 3

That is a property of the default allowMultiQueries=false, not a defence. The OR '1'='1' read above needed no stacking at all, and turning allowMultiQueries on for a batch job removes even that accident.

Two things to add before this is production code

Give the application its own account. The runs above connected as a scratch user holding SELECT, INSERT, UPDATE, DELETE on one schema, not as root. That single change caps what any injection or bug can reach.

Open a connection pool, not a connection per operation. Every example here calls DriverManager.getConnection inline, which is fine for a demonstration and wrong in a server. Use HikariCP or your framework’s pool, and wrap multi-statement writes in setAutoCommit(false) … commit() so a failure halfway cannot leave the rows inconsistent.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.