Skip to content

Create a sql table and execute stuff

This example shows how to create a SQL table and execute queries.

The Core API provides utilities to create tables, load data and execute updates.

→ Deep dive: [[Base Execution|Core-API/Data-Infrastructure/MySQL/Base-Execution]] & [[Table Creation|Core-API/Data-Infrastructure/MySQL/Table-Creation]]


Steps

  1. Create a table (simple or via adapter)
  2. Execute queries (SELECT / UPDATE)
  3. Process results
  4. Handle exceptions properly

Simple table creation

try {
    sqlUser.createTable(
            TABLE_NAME,
            "create table base_player_data" +
                    "   (" +
                    "    player_id  int                                 null primary key," +
                    "    name       varchar(17)                         not null," +
                    "    first_join timestamp default CURRENT_TIMESTAMP not null," +
                    "    last_quit  timestamp default CURRENT_TIMESTAMP not null" +
                    ");"
    );
} catch (SQLException exception) {
    logger.log(Level.WARNING, "Failed to create table base_player_data!", exception);
}

Table adapter (for multiple tables)

Define the adapter

public class ExampleTableAdapter extends TableAdapter {

  @Table
  public static final SQLTable BASE_PLAYER_DATA = new SQLTable(
          "base_player_data",
          "create table base_player_data" +
                  "   (" +
                  "    player_id  int                                 null primary key," +
                  "    name       varchar(17)                         not null," +
                  "    first_join timestamp default CURRENT_TIMESTAMP not null," +
                  "    last_quit  timestamp default CURRENT_TIMESTAMP not null" +
                  ");"
  );

  @Table
  public static final SQLTable PLAYER_JOIN_LOG = new SQLTable(
          "player_join_log",
          "create table player_join_log" +
                  "   (" +
                  "    id        int auto_increment primary key," +
                  "    player_id int       not null," +
                  "    date      timestamp null" +
                  ");"
  );

  public ExampleTableAdapter(@NotNull String schema) {
      super(schema);
  }

}

Register / validate the adapter

ExampleTableAdapter adapter = new ExampleTableAdapter("example");
SQLHandler sqlHandler = BukkitCoreLibrary.getSQLHandler();
try {
    sqlHandler.validateTableAdapter(sqlUser, adapter);
} catch (SQLException | IllegalAccessException exception) {
    logger.log(Level.WARNING, "Failed to validate table adapter!", exception);
}

Example queries

Load data

String table = ExampleTableAdapter.BASE_PLAYER_DATA.getTable();
try {
    SQLResult result = sqlUser.getSQLResult(
            "SELECT name, first_join, last_quit" +
                    "   FROM " + table +
                    "   WHERE player_id = ?;",
            playerId
    );

    SQLRow row = result.getFirstOrNull();
    if (row != null) {
        Timestamp firstJoin = row.getTimestamp("first_join");
        Timestamp lastQuit = row.getTimestamp("last_quit");

        logger.info(playerId + "'s data: " + firstJoin + " " + lastQuit);
    }
} catch (SQLException exception) {
    logger.log(Level.WARNING, "Failed to load data!", exception);
}

Update data

try {
    sqlUser.executeQuery(
            "UPDATE " + table +
                    "   SET last_quit = ?" +
                    "   WHERE player_id = ?;",
            quit, playerId
    );
} catch (SQLException exception) {
    logger.log(Level.WARNING, "Failed to update data!", exception);
}

Explanation

  • SQLUser is used to execute queries
  • createTable(...) creates a single table
  • TableAdapter is used for managing multiple tables
  • SQLResult / SQLRow are used to read query results
  • executeQuery(...) executes updates

Notes

  • Use createTable(...) for single tables
  • Use a TableAdapter when working with multiple tables
  • Always store table names as constants (type safety)
  • Always handle SQLException properly

Next step

[[Create persistent player data|Core-API/Build-your-first-feature/Data-&-Persistence/Create-persistent-player-data]]