Baza danych

SQL

Sponge zapewnia wygodną abstrakcję dla ustanowienia połączeń bazy danych które radzą sobie ze złożonościami ustanowienia wydajnego połączenia z JDBC URL.

While the SQL service supports any JDBC connector, the Forge implementation of Sponge only ships with the most common:

  • MySQL

  • Sqlite

  • H2

Ostrzeżenie

Because Sqlite has many limitations, its usage is strongly discouraged except in cases where legacy compatibility is required. H2 is our recommended file-backed database implementation.

Sposób użycia

A data source can be accessed through the plugin’s service manager:

import org.spongepowered.api.Sponge;
import org.spongepowered.api.service.sql.SqlService;

import java.sql.Connection;
import java.sql.SQLException;

private SqlService sql;
public javax.sql.DataSource getDataSource(String jdbcUrl) throws SQLException {
    if (sql == null) {
        sql = Sponge.getServiceManager().provide(SqlService.class).get();
    }
    return sql.getDataSource(jdbcUrl);
}

// Later on
public void myMethodThatQueries() throws SQLException {
    Connection conn = getDataSource("jdbc:h2:imalittledatabaseshortandstout.db").getConnection();
    try {
        conn.prepareStatement("SELECT * FROM test_tbl").execute();
    } finally {
        conn.close();
    }

}

The SQL service provides a pooled connection, so getting a connection from the returned DataSource is not expensive. Therefore, we recommended not keeping connections around, and closing them soon after use instead, as shown in the above example. (Proper resource management means you do have to close connections).

NoSQL

Na obecną chwilę Sponge nie zapewnia żadnej specjalnej abstrakcji w bazach danych NoSQL (MongoDB itp.). Wtyczki, które chcą korzystać z baz danych NoSQL, muszą dostarczyć własne konektory.