Advertisement
Guest User

MySQL

a guest
Mar 13th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. public class MySQL {
  2.  
  3. private String host;
  4. private String port;
  5. private String database;
  6. private String username;
  7. private String password;
  8.  
  9. private Connection connection;
  10.  
  11. public void connect() {
  12. if (!isConnected()) {
  13.  
  14. /*
  15.  
  16. Alright so here is where you would want to define the values of host, port, database, username, and password
  17.  
  18. I am just going to assume that your config.yml has all that information and looks something like this:
  19.  
  20. Host: "host"
  21. Port: "3306"
  22. Database: "database"
  23. Username: "username"
  24. Password: "password"
  25.  
  26. here just simply gain access to your main class using Dependency Injections and you will be able to
  27. get your config if you are not using a config then just simply do the following:
  28.  
  29. this.host = "host";
  30. this.port = "3306";
  31. this.database = "database";
  32. this.username = "username";
  33. this.password = "password";
  34.  
  35. */
  36.  
  37. try {
  38.  
  39. connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);
  40.  
  41. } catch (SQLException e) {
  42. e.printStackTrace();;
  43. }
  44. }
  45. }
  46.  
  47. public void disconnect() {
  48. if (isConnected()) {
  49.  
  50. try {
  51. connection.close();
  52. } catch (SQLException e) {
  53. e.printStackTrace();
  54. }
  55.  
  56. }
  57. }
  58.  
  59. public boolean isConnected() {
  60. return (connection == null ? false : true);
  61. }
  62.  
  63. public Connection getConnection() {
  64. return connection;
  65. }
  66.  
  67. public void createTable() {
  68. if (!isConnected()) {
  69. connect();
  70. }
  71.  
  72. try {
  73. PreparedStatement ps = connection.prepareStatement("CREATE TABLE IF NOT EXISTS [TABLE NAME HERE] (UUID VARCHAR(50),NAME VARCHAR(20))");
  74. ps.executeUpdate();
  75. } catch (SQLException e) {
  76. e.printStackTrace();
  77. }
  78. }
  79.  
  80. public void insertIP(Player player) {
  81. if (!isConnected()) {
  82. connect();
  83. }
  84.  
  85. try {
  86.  
  87. PreparedStatement ps = connection.prepareStatement("INSERT INTO [YOUR TABLE NAME] (UUID,NAME) VALUES (?,?)");
  88.  
  89. ps.setString(1, player.getUniqueId().toString());
  90. ps.setString(2, player.getName());
  91.  
  92. ps.executeUpdate();
  93. } catch (SQLException e) {
  94. e.printStackTrace();
  95. }
  96. }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement