MySQL Driver?

Hello, I’m using Apache DBCP2 for a MySQL connection pool solution using BasicDataSource.

Looks like Sponge doesn’t provide a default mysql driver

Error: Database init failure: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'

Should I shade a driver in my plugin or what?

You might want to take a look at this

https://docs.spongepowered.org/stable/en/plugin/database.html

Yes, I’ve looked at that and it means I’ll have to write an extra MySQL class for Sponge.

Do you know why Sponge keeps SQLite driver available while MySQL driver is not available the same way?

Class.forName("org.sqlite.JDBC"); //works 
Class.forName("org.mysql.jdbc.Driver"); //doesn't work

You can find a driver here https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.13 it is most likely available in maven-central as well.

EDIT: I’d also recommend taking a look at GitHub - brettwooldridge/HikariCP: 光 HikariCP・A solid, high-performance, JDBC connection pool at last. for all your connection pooling needs :slight_smile:

I decided it was easier to extend the existing class I had for Bukkit by overriding the method that set up the DataSource for the database - ended up with a new MySQL class that just a single overridden method.

I think that’s better than shading 2.1mb of unnecessary mysql driver classes into the plugin.

Use this

public Connection openConnection() {
	String url = "jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database;
        Properties properties = new Properties();
        properties.setProperty("user", this.user);
        properties.setProperty("password", this.password);
        properties.setProperty("useSSL", "false");
		try {
			this.connection = DriverManager.getConnection(url, properties);
		} catch (SQLException e) {
			System.out.println("JDBC Driver not found!");
			e.printStackTrace();
		}
		return this.connection;
	}

Did you guys actually read the docs?
MySQL (and MariaDB) is available.

Use the Sponge SqlService to get a connection (which btw. also uses HikariCP):

// Get Sponge SQL-Service
SqlService service = Sponge.getServiceManager().provide(SqlService.class).get();
// Get Connection URL from Sponge config or your own config however you want.
String url = service.getConnectionUrlFromAlias(SQL_ID).orElse("jdbc:mysql://minecraft@localhost:3306/minecraft");
// Finally get your pooled datasource:
try {
    dataSource = service.getDataSource(url);
    // And do stuff with it ...
}
catch (SQLException e) {
    e.printStackTrace();
}

Since I was already using a DataSource for my MySQL on the Bukkit/Bungee version I was able to do this

this.dataSource = sqlServiceProvider.get().getDataSource(
                "jdbc:mysql://" + username + ":" + password + "@" + url
        );