Skip to content

Using the DatabaseAPI

ancap-kun edited this page Feb 17, 2023 · 2 revisions

DatabaseAPI - API for working with databases.

Description

DatabaseAPI provides a few lines to connect your plugin to a database - SQL or based on Bukkit configs (not recommended to use, left to maintain backward compatibility with legacy code). What's noteworthy - you don't need to worry about what kind of database it is at all inside the code - all database connections are fully configured in AncapPlugin's config.yml.

Getting started

This is roughly what a database connection looks like:

private SQLDatabase database; // SQLDatabase provides several ways of accessing the database, including via the bare Connection from JDBC and via ORMLite

private void loadDatabase() {
    this.database = new DatabaseFromConfig(
            this, // JavaPlugin
            AncapPluginConfig.loaded().getDatabaseConnectionSection(), // Here is the ConfigurationSection with the connection settings, about it below
    ).load();
}

After the connection, you can work with SQLDatabase however you want, including using the ORMLite added to it to store your data.

Setting up a connection

DatabaseAPI is able to read the database connection settings in the following standard in .yml files:

connection:
  # database type - from those available (see [[Database Types]])
  type: sqlite
  remote:
    host: "127.0.0.1"
    name: "ancap-plugin-database"
    user: "ancap-plugin-user"
    password: "qwerty"
    port: 3306
  file:
    name: "langs.db"

From the example above, in order for the loader to read the settings, it needs to pass the configuration section named connection in the .yml file above. That is, for the specific example above, from the root ConfigurationSection call section.getConfigurationSection("connection").

Database from config

It's even easier to configure than a SQL database, and it's done through the ConfigurationDatabase.builder() builder. You can configure the frequency of the autosave and the file in which the database will be written. You can also tell the framework to create it for you, without creating the database file yourself. In that case you will only have to pass your plugin object (JavaPlugin).

Here is an example:

AncapPay.DATABASE = ConfigurationDatabase.builder()
    .autoSave(10)
    .plugin(this)
    .build();

Clone this wiki locally