MySQL database integration with your plugin. - Historical

Applied By neilnet: Nov 7, 2013 at 11:02 AM

MySQL database integration with your plugin.
Due to the lack of tutorials on how to use mySQL in a plugin, I've decided to create a tutorial for my self.

Tutorial status: Unfinished.
Last update: 7th november 2013.


You need to install JDBC first, it's available from:

Basic explanation on JDBC
If you're wondering what is JDBC
It's a .jar file which let's you connect to mySQL databases and run mySQL queries.

Select .zip if you run windows, select .tar if you have a mac.
Extract it with a program like Winrar or 7Zip.

Once that's done, we're going to want to add it to our project.

You add it the same way you added Craftbukkit.jar into your Java Build path. So first select Java build path and then click on libraries, and then click on add external jars. Locate to the place you downloaded the JDBC connector and click OK.

My favourite part, the coding!

We must create a few variables that can let us connect to the database. This is what we need to create.

Code (Text):
        //DataBase vars.
        final String username="YOUR DB USERNAME"; //Enter in your db username
        final String password="YOUR DB PASSWORD"; //Enter your password for the db
        final String url = "jdbc:mysql://"; //Enter URL w/db name
        //Connection vars
        static Connection connection; //This is the variable we will use to connect to database
Now we need to connect to the database using the Connection variable we made that is provided by Java. We do this by assigning properties to our connection variable in the onEnable and then trying to connect. This is the code we need to use:

Again, put this code in the onEnable(); method because we're trying to connect as soon as we start the server.
Code (Text):
try { //We use a try catch to avoid errors, hopefully we don't get any.
                    Class.forName("com.mysql.jdbc.Driver"); //this accesses Driver in jdbc.
                } catch (ClassNotFoundException e) {
                try { //Another try catch to get any SQL errors (for example connections errors)
                    connection = DriverManager.getConnection("url,username,password);
                    //with the method getConnection() from DriverManager, we're trying to set
                    //the connection's url, username, password to the variables we made earlier and
                    //trying to get a connection at the same time. JDBC allows us to do this.
                } catch (SQLException e) { //catching errors)
                    e.printStackTrace(); //prints out SQLException errors to the console (if any)
Now it's time to let our plugin close the connection, since we don't want useless connections still lingering around. We're going to do this by closing the connection variable in the onDisable() method. So when the server closes, we don't need the connection to still be there anymore.