Quick & Simple SQLite

Discussion in 'Resources' started by Rprrr, Aug 23, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    Rprrr

    Hai der,

    Just wanted to post this quick & simple class that can be used to create & access a SQLite database file in your plugin's folder.

    It's probably not perfect, since it's the first time I've posted something in this section and I'm obviously not the best coder in the world, but I hope this is somewhat useful for others.

    The following would create a 'database.db' file in your plugin's folder.

    Code:
    package me.rprrr.test.sqlite;
     
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    import org.bukkit.plugin.Plugin;
     
    public class Main {
       
        private static Logger l = me.rprrr.creed.Main.l;   
        private static String path;
       
        public Main(Plugin plugin) {
            l = plugin.getLogger();
           
            try {
                Class.forName("org.sqlite.JDBC");
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();           
                l.log(Level.SEVERE, "Couldn't load the sqlite-JDBC driver.");
            }
     
            path = plugin.getDataFolder().getAbsolutePath();
            l.info("Path to plugin datafolder that will be used: " + path);
        }
     
        public static Connection getConnection(){       
            Connection connection = null;       
            try {
                connection = DriverManager.getConnection("jdbc:sqlite:" + path + "/database.db");
            } catch (SQLException e1) {
                e1.printStackTrace();
                l.log(Level.SEVERE, "Failed to get the connection with the database.db file.");
            }       
            return connection;       
        }
       
        public static void closeConnection(Connection connection) {
            try {
                if (connection !=null) {
                    connection.close();
                }
            }
            catch (SQLException e) {
                //Failed to close the connection.
                System.err.println(e);
            }
        }
       
    }
    
     
Thread Status:
Not open for further replies.

Share This Page