Advertisement
Guest User

Untitled

a guest
Jun 28th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. import com.mysql.jdbc.Connection;
  2. import org.bukkit.plugin.java.JavaPlugin;
  3.  
  4. import java.sql.DriverManager;
  5. import java.sql.SQLException;
  6.  
  7. public class Main extends JavaPlugin {
  8.  
  9. //DataBase vars.
  10. final String username="root"; //Enter in your db username
  11. final String password="password"; //Enter your password for the db
  12. final String url = "jdbc:mysql://localhost:3306/tutorial"; //Enter URL w/db name
  13.  
  14. //Connection vars
  15. static Connection connection; //This is the variable we will use to connect to database
  16.  
  17. @Override
  18. public void onEnable(){
  19.  
  20. try { //We use a try catch to avoid errors, hopefully we don't get any.
  21. Class.forName("com.mysql.jdbc.Driver"); //this accesses Driver in jdbc.
  22. } catch (ClassNotFoundException e) {
  23. e.printStackTrace();
  24. System.err.println("jdbc driver unavailable!");
  25. return;
  26. }
  27. try { //Another try catch to get any SQL errors (for example connections errors)
  28. connection = (Connection) DriverManager.getConnection(url,username,password);
  29. //with the method getConnection() from DriverManager, we're trying to set
  30. //the connection's url, username, password to the variables we made earlier and
  31. //trying to get a connection at the same time. JDBC allows us to do this.
  32. } catch (SQLException e) { //catching errors)
  33. e.printStackTrace(); //prints out SQLException errors to the console (if any)
  34. }
  35.  
  36.  
  37. }
  38.  
  39. @Override
  40. public void onDisable(){
  41.  
  42. // invoke on disable.
  43. try { //using a try catch to catch connection errors (like wrong sql password...)
  44. if (connection!=null && !connection.isClosed()){ //checking if connection isn't null to
  45. //avoid receiving a nullpointer
  46. connection.close(); //closing the connection field variable.
  47. }
  48. } catch(Exception e) {
  49. e.printStackTrace();
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement