Skip to lesson

Running SQL scripts at startup

A new laptop or test database starts empty, and setting it up by hand from a README always loses a step. The app could build its own tables and demo data, if running the setup twice is harmless.

schema.sql and seed.sql in src/main/resources

A schema script (schema.sql) holds the CREATE TABLE statements for the app's tables. A seed script (seed.sql) holds INSERT statements for starting data. Both live in src/main/resources, so they travel inside the build.

ShopLite's scripts come straight from the SQL section's design, with one change: the tables use CREATE TABLE IF NOT EXISTS, and the DROP TABLE line is gone. A startup script must never delete data.

SQL
-- src/main/resources/schema.sql (first table; the other five follow the same pattern)CREATE TABLE IF NOT EXISTS customers (  customer_id INT          NOT NULL AUTO_INCREMENT PRIMARY KEY,  full_name   VARCHAR(100) NOT NULL,  email       VARCHAR(255) NOT NULL,  phone       VARCHAR(15)  NULL,  created_at  DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,  CONSTRAINT uq_customers_email UNIQUE (email));
-- src/main/resources/seed.sql (first statement)INSERT INTO customers (full_name, email, phone, created_at) VALUES  ('Asha Rao', 'asha.rao@example.com', '9876543201', '2026-05-04 10:15:00'),  ('Ravi Kumar', 'ravi.kumar@example.com', '9876543202', '2026-05-19 18:40:00');

Without scripts, every new team member, every college lab PC and every test database has to be set up by hand from instructions in a README, and someone always misses a step. With them, the app can read the scripts from the classpath and prepare its own database.

Reading a script from the classpath and running it statement by statement

Splitting a script means cutting the text of an SQL file into single statements, because JDBC runs one statement per execute call and cannot take a whole file at once.

Example 1 is the splitter: it cuts a script at every ; that ends a line. Example 2 runs schema.sql and seed.sql with it.

Example 1 · Splitting a script into statements

SqlScriptSplitDemo.javaJava
import java.util.ArrayList;import java.util.List;
// Splits a script into statements: a statement ends with ';' at the end of a line.// Simplified on purpose: no ';' at the end of a line inside a string, no DELIMITER blocks.class SqlScript {    static List<String> split(String script) {        List<String> statements = new ArrayList<>();        StringBuilder current = new StringBuilder();        for (String line : script.split("\\R")) {          // \R = any line break, Windows or macOS            String trimmed = line.trim();            if (trimmed.isEmpty() || trimmed.startsWith("--")) {                continue;            }            current.append(line).append('\n');            if (trimmed.endsWith(";")) {                String sql = current.toString().trim();                statements.add(sql.substring(0, sql.length() - 1));                current.setLength(0);            }        }        if (!current.toString().isBlank()) {            statements.add(current.toString().trim());        }        return statements;    }}
public class SqlScriptSplitDemo {    public static void main(String[] args) {        String script = """                -- Categories for the college fest stall                CREATE TABLE IF NOT EXISTS categories (                  category_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,                  name        VARCHAR(50) NOT NULL                );
                INSERT INTO categories (name) VALUES ('Books');                INSERT INTO categories (name)                  VALUES ('Fashion');                SELECT COUNT(*) FROM categories                """;
        List<String> statements = SqlScript.split(script);        System.out.println(statements.size() + " statements:");        for (int i = 0; i < statements.size(); i++) {            String firstLine = statements.get(i).lines().findFirst().orElse("");            int lineCount = (int) statements.get(i).lines().count();            System.out.println("  " + (i + 1) + ". " + firstLine + "  [" + lineCount + " line(s)]");        }    }}
Output
4 statements:
  1. CREATE TABLE IF NOT EXISTS categories (  [4 line(s)]
  2. INSERT INTO categories (name) VALUES ('Books')  [1 line(s)]
  3. INSERT INTO categories (name)  [2 line(s)]
  4. SELECT COUNT(*) FROM categories  [1 line(s)]

What this code does

  • A statement ends where a line ends with ;. Blank lines and -- comment lines are skipped, so a ; inside a comment can never end a statement.
  • The ; itself is cut off, because JDBC runs one statement per call and the MySQL driver rejects a trailing ; followed by more text. The last statement may have no ; at all.
  • This is a simplified splitter: it would break on a string value that ends a line with ;, and on stored procedures with DELIMITER. ShopLite's scripts contain neither.

Example 2 · DatabaseInitializerDemo.java: schema.sql, then seed.sql into empty tables

Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database

DatabaseInitializerDemo.javaJava
import com.zaxxer.hikari.HikariConfig;import com.zaxxer.hikari.HikariDataSource;
import java.io.IOException;import java.io.InputStream;import java.io.UncheckedIOException;import java.nio.charset.StandardCharsets;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.List;import javax.sql.DataSource;
class DatabaseInitializer {    private final DataSource dataSource;
    DatabaseInitializer(DataSource dataSource) {        this.dataSource = dataSource;    }
    void initialize() {        try (Connection con = dataSource.getConnection()) {            int created = runScript(con, "schema.sql");            System.out.println("schema.sql: " + created + " statements run");
            if (hasRows(con)) {                System.out.println("seed.sql: skipped, the tables already have data");                return;            }            con.setAutoCommit(false);              // all demo rows or none            try {                int inserted = runScript(con, "seed.sql");                con.commit();                System.out.println("seed.sql: " + inserted + " statements run");            } catch (SQLException | RuntimeException e) {                con.rollback();                throw e;            } finally {                con.setAutoCommit(true);            }        } catch (SQLException e) {            throw new IllegalStateException("Database setup failed: " + e.getMessage(), e);        }    }
    private static boolean hasRows(Connection con) throws SQLException {        try (Statement st = con.createStatement();             ResultSet rs = st.executeQuery("SELECT EXISTS (SELECT 1 FROM categories)")) {            rs.next();            return rs.getBoolean(1);        }    }
    static int runScript(Connection con, String resource) throws SQLException {        List<String> statements = SqlScript.split(readResource(resource));        try (Statement st = con.createStatement()) {            for (int i = 0; i < statements.size(); i++) {                try {                    st.execute(statements.get(i));                } catch (SQLException e) {                    throw new SQLException(resource + ", statement " + (i + 1) + ": " + e.getMessage(),                            e.getSQLState(), e.getErrorCode(), e);                }            }        }        return statements.size();    }
    static String readResource(String name) {        try (InputStream in = DatabaseInitializer.class.getClassLoader().getResourceAsStream(name)) {            if (in == null) {                throw new IllegalStateException(name + " was not found in src/main/resources");            }            return new String(in.readAllBytes(), StandardCharsets.UTF_8);        } catch (IOException e) {            throw new UncheckedIOException("Could not read " + name, e);        }    }}
public class DatabaseInitializerDemo {    public static void main(String[] args) throws SQLException {        HikariConfig config = new HikariConfig();        config.setJdbcUrl(System.getenv("DB_URL"));        config.setUsername(System.getenv("DB_USER"));        config.setPassword(System.getenv("DB_PASSWORD"));
        try (HikariDataSource dataSource = new HikariDataSource(config)) {            new DatabaseInitializer(dataSource).initialize();
            try (Connection con = dataSource.getConnection();                 Statement st = con.createStatement();                 ResultSet rs = st.executeQuery(                         "SELECT (SELECT COUNT(*) FROM products), (SELECT COUNT(*) FROM orders)")) {                rs.next();                System.out.println("Products: " + rs.getInt(1) + ", orders: " + rs.getInt(2));            }        }    }}
Sample output
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
[main] INFO com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@696da30b
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
schema.sql: 6 statements run
seed.sql: 6 statements run
Products: 15, orders: 16
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.

What this code does

  • readResource loads the script from the classpath, SqlScript.split (from Example 1, in its own file next to this one) cuts it up, and one Statement runs the pieces in order. An error names the script and the statement number.
  • The seed runs in one transaction: if any insert fails, rollback() removes the rows already inserted, so the tables never end up half filled.
  • The run above starts from an empty database: the six CREATE TABLE IF NOT EXISTS create every table, and the six INSERT statements load the demo data.

Read the file with getResourceAsStream and readAllBytes() as UTF-8, split it at a ; at the end of a line while skipping comments, and run each piece with Statement.execute on the same connection. There are no user values in these scripts, so a plain Statement is fine here.

When a statement fails, say which one. seed.sql, statement 4: Duplicate entry ... is fixed in a minute; a bare SQLException in the middle of startup is not.

Trace the code

Follow the splitting loop

Step through a script with a comment and two statements.

public class SplitDemo {
public static void main(String[] args) {
String[] lines = { "-- seed", "INSERT 1;", "INSERT 2;" };
int count = 0;
for (String line : lines) {
if (line.startsWith("--")) {
continue;
}
if (line.endsWith(";")) {
count++;
System.out.println("Statement " + count + ": " + line);
}
}
System.out.println("Total: " + count);
}
}

Variables

None yet.

Output

(nothing printed yet)

Line 3The script has three lines: one comment and two statements.

Step 1 of 13

Idempotent scripts: CREATE TABLE IF NOT EXISTS and safe seed inserts

An idempotent script gives the same result whether it runs once or ten times. Startup scripts must be idempotent, because the app runs them on every start.

Example 3 runs the initializer a second time. Example 4 shows what a plain CREATE and INSERT do on a second start.

Example 3 · Running the initializer a second time

Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database

Terminal
mvn -q compile exec:java -Dexec.mainClass=DatabaseInitializerDemo
Sample output
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
[main] INFO com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@696da30b
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
schema.sql: 6 statements run
seed.sql: skipped, the tables already have data
Products: 15, orders: 16
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.

What this code does

  • The same program on the same database: CREATE TABLE IF NOT EXISTS does nothing for tables that exist (MySQL only records a note), and the seed is skipped because categories already has rows.
  • Still 15 products and 16 orders, not 30 and 32. That is what "safe to run more than once" means.

Example 4 · Mistake: scripts that only work the first time

Runs in: a Maven project with the MySQL driver and the ShopLite database

RunTwiceMistakeDemo.javaJava
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;
public class RunTwiceMistakeDemo {    static void run(Connection con, String label, String sql) {        try (Statement st = con.createStatement()) {            st.execute(sql);            System.out.println(label + ": OK");        } catch (SQLException e) {            System.out.println(label + ": error " + e.getErrorCode() + ", " + e.getMessage());        }    }
    public static void main(String[] args) throws SQLException {        MysqlDataSource dataSource = new MysqlDataSource();        dataSource.setURL(System.getenv("DB_URL"));        dataSource.setUser(System.getenv("DB_USER"));        dataSource.setPassword(System.getenv("DB_PASSWORD"));
        String create = "CREATE TABLE coupons (code VARCHAR(20) PRIMARY KEY, discount INT NOT NULL)";        String insert = "INSERT INTO coupons (code, discount) VALUES ('FEST50', 50)";
        try (Connection con = dataSource.getConnection()) {            run(con, "1st start, CREATE TABLE", create);            run(con, "1st start, INSERT      ", insert);            run(con, "2nd start, CREATE TABLE", create);            run(con, "2nd start, INSERT      ", insert);
            System.out.println("Safe versions on the 2nd start:");            run(con, "  CREATE TABLE IF NOT EXISTS", create.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));            run(con, "  INSERT IGNORE             ", insert.replace("INSERT", "INSERT IGNORE"));            run(con, "  DROP (clean up the demo)  ", "DROP TABLE coupons");        }    }}
Output
1st start, CREATE TABLE: OK
1st start, INSERT      : OK
2nd start, CREATE TABLE: error 1050, Table 'coupons' already exists
2nd start, INSERT      : error 1062, Duplicate entry 'FEST50' for key 'coupons.PRIMARY'
Safe versions on the 2nd start:
  CREATE TABLE IF NOT EXISTS: OK
  INSERT IGNORE             : OK
  DROP (clean up the demo)  : OK

What this code does

  • A plain CREATE TABLE fails with error 1050 once the table exists, and a plain INSERT of a fixed key fails with 1062. An app whose startup script does this works on day one and refuses to start on day two.
  • IF NOT EXISTS skips an existing table; INSERT IGNORE skips rows whose key is already there. Both turn the error into a warning.

For tables, use CREATE TABLE IF NOT EXISTS. For seed rows there are three common tools:

  • Seed only when empty: check SELECT EXISTS (SELECT 1 FROM categories) and skip the whole seed if there are rows. ShopLite does this, because its demo orders refer to rows by number.
  • INSERT IGNORE: skips rows whose primary or unique key already exists. It also hides some other errors as warnings, so use it only for simple reference rows.
  • INSERT ... SELECT ... WHERE NOT EXISTS (...): inserts a row only if a matching row is missing; works even without a unique key.

Fix the error

Make the script safe to repeat

Read the real error, then pick the line that fixes it.

Round 1 of 2

The app fails on its second start.

CREATE TABLE coupons (
code VARCHAR(20) PRIMARY KEY,
discount INT NOT NULL
);

Error

ERROR 1050 (42S01): Table 'coupons' already exists

Running scripts only when db.init=true

db.init is a configuration switch: when it is true, startup runs schema.sql and seed.sql; when it is false (the default), the app uses the database exactly as it finds it.

The check lives in main, next to the rest of the wiring, and its value comes from AppConfig, so DB_INIT=true in the environment turns the scripts on for one run.

Java
try (HikariDataSource dataSource = DataSourceFactory.create(config)) {    if (config.dbInit()) {        new DatabaseInitializer(dataSource).initialize();    }    // ... create DAOs and services, run the menu}

The default is off on purpose. On your laptop you turn it on once to build a fresh database. On a shared or production database, nobody wants a program to create tables or insert demo rows just because it started.

Order of execution

Order the startup

Tap the steps ShopLite takes at startup, in order.

Why real projects use migration tools (Flyway, later in the course)

A migration tool, such as Flyway, keeps numbered change scripts and a history table that records which ones have run. On startup it runs only the new ones, in order, exactly once.

Startup scripts create a database from nothing, but they cannot change an existing one. When ShopLite later needs a rating column on products, CREATE TABLE IF NOT EXISTS does nothing, because the table already exists.

SQL
-- Flyway style: each change is a new, numbered file that runs once-- V1__create_tables.sqlCREATE TABLE products (product_id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(120) NOT NULL);
-- V2__add_product_rating.sqlALTER TABLE products ADD COLUMN rating DECIMAL(2,1) NULL;

Without a migration tool, every copy of the database must be altered by hand. With Flyway, the change is the second file above, V2__add_product_rating.sql, and it runs once on each database.

Section 16 moves ShopLite to Flyway. Until then, schema.sql plus db.init is simple and honest for a project that is still taking shape.

Next step

Check your understanding

12 quick questions