Advertisement
Isigar

Connection mysql

Dec 22nd, 2018
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. package cz.relisoft.mysql;
  2.  
  3. import java.sql.SQLException;
  4.  
  5. import org.bukkit.configuration.file.FileConfiguration;
  6.  
  7. import cz.relisoft.plugin.Main;
  8.  
  9. import java.io.File;
  10. import java.sql.Connection;
  11. import java.sql.DriverManager;;
  12.  
  13. public class CustomConnection {
  14.  
  15.     private Connection connection;
  16.     private String host,db,pass,user;
  17.     private int port = 3306;
  18.    
  19.     private Main plugin;
  20.    
  21.     public CustomConnection(Main main) {
  22.         this.plugin = main;
  23.         FileConfiguration config = main.getConfig();
  24.         config.addDefault("port", 3306);
  25.         config.addDefault("host","localhost");
  26.         config.addDefault("user", "root");
  27.         config.addDefault("pass","");
  28.         config.addDefault("db", "test");
  29.         config.options().copyDefaults(true);
  30.         main.saveConfig();
  31.        
  32.         this.host = config.getString("host");
  33.         this.db = config.getString("db");
  34.         this.pass = config.getString("pass");
  35.         this.user = config.getString("user");
  36.         this.port = config.getInt("port");
  37.     }
  38.    
  39.     public void connect() throws SQLException, ClassNotFoundException {
  40.         if(connection != null && !connection.isClosed()) {
  41.             return;
  42.         }
  43.        
  44.         synchronized (this) {
  45.             if(connection != null && !connection.isClosed()) {
  46.                 return;
  47.             }
  48.             Class.forName("com.mysql.jdbc.Driver");
  49.             connection = DriverManager.getConnection("jdbc:mysql://"+this.host+":"+this.port+"/"+this.db, this.user, this.pass);
  50.         }
  51.     }
  52.    
  53.     public Connection getConnection() throws ClassNotFoundException, SQLException {
  54.         if(connection == null || connection.isClosed()) {
  55.             this.connect();
  56.         }
  57.         return this.connection;
  58.     }
  59.    
  60.     public void close() throws SQLException {
  61.         this.connection.close();
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement