Importing mysql Driver

Hey,

I have been trying for quite some times already and have been through some tutorials, but i need some help.

I want to use a MySql Database in order to allow my plugin to easily manage multiples data.
Here is the code I am using to create a database:

try {
            Class.forName( "com.mysql.jdbc.Driver" );
            System.out.println("driver: ok");
            
            String url = "jdbc:mysql://localhost/";
            String user = "root";
            String pass = "mypassword";
            
            Connection conn = DriverManager.getConnection(url, user, pass);
            Statement state = conn.createStatement();
            state.executeQuery("CREATE DATABASE MyDataBase");

            state.close();

        } catch ( ClassNotFoundException | SQLException e ) {
            System.out.println("===error===");
        }

By runing the plugin with the server, I only receive the error message, so i guess the issue comes from the importation of the Driver.
I already cofigured the project to add the external library “mysql-connector-java-5.1.38-bin.jar” that contains the Driver.
I don’t know if I need to give the Jar to the server, so that it could understand, and how to do so.

So I came here with hope that someone could explain me what are the requiered code and configurations
to make this thing work.

You don’t need to do all that. Sponge has its own SQL service.

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

2 Likes

Oh!
You mean that I just need to write the fuction “getDataSource”
Then I call it like in the second function “myMethodThatQueries” to interact with the database ?

And “imalittledatabaseshortandstout.db” is the name of the database I want ?

How to change Directory? If i want the database to be in a specific folder ?

any help about directories ?

the database is not created in the server folder but in my user folder:

C:\Users\Me\

How do i change that ?

Here’s an example using H2 database

SqlService sql = Sponge.getGame().getServiceManager().provide(SqlService.class).get();
DataSource source = sql.getDataSource("jdbc:h2:./config/myplugin/imalittledatabaseshortandstout");
Connection connection = source.getConnection();
...

Using mysql you can do something like this

source = sql.getDataSource(“jdbc:mysql://” + username + “:” + password + “@” + url);

I think sqlite is this but I cannot confirm as it’s not recommended to use sqlite.

source = sql.getDataSource(“jdbc:sqlite:./config/myplugin/imalittledatabaseshortandstout”);

This was pulled out of the air so it’s probably not completely accurate but should get you in the right direction