· 10 years ago · Mar 18, 2016, 02:18 PM
1package Refez.Tokens.MySQL;
2
3import Refez.Tokens.Main.Main;
4import java.sql.Connection;
5import java.sql.DriverManager;
6import java.sql.ResultSet;
7import java.sql.SQLException;
8import java.sql.Statement;
9import org.bukkit.Bukkit;
10import org.bukkit.command.ConsoleCommandSender;
11import org.bukkit.configuration.file.FileConfiguration;
12
13public class MySQL
14{
15 public static Connection con;
16
17 public static Connection connect()
18 {
19 if (!hasConnection()) {
20 try
21 {
22 con = DriverManager.getConnection(
23 "jdbc:mysql://" + Main.stg.getString("ip") + ":3306/" +
24 Main.stg.getString("database") +
25 "?autoReconnect=true",
26 Main.stg.getString("username"),
27 Main.stg.getString("password"));
28 Bukkit.getConsoleSender().sendMessage(
29 Main.prefix + "§aSuccessfully connected to MySQL.");
30 Bukkit.broadcastMessage(Main.prefix + "§aSuccesfully connected to MySQL.§7§o(Tokens)");
31 }
32 catch (SQLException e)
33 {
34 Bukkit.getConsoleSender().sendMessage(
35 Main.prefix + "§cFailed to connect to MySQL: " +
36 e.getMessage());
37 e.printStackTrace();
38 }
39 }
40 return con;
41 }
42
43 public static void close()
44 {
45 if (hasConnection()) {
46 try
47 {
48 if (con != null)
49 {
50 con.close();
51 Bukkit.getConsoleSender()
52 .sendMessage(
53 Main.prefix +
54 "§cSuccessfully disconnected from MySQL.");
55 }
56 }
57 catch (SQLException e)
58 {
59 Bukkit.getConsoleSender().sendMessage(
60 Main.prefix + "§cFailed to disconnect from MySQL: " +
61 e.getMessage());
62 e.printStackTrace();
63 }
64 }
65 }
66
67 public static void update(String qry)
68 {
69 if (hasConnection()) {
70 try
71 {
72 Statement st = con.createStatement();
73 st.executeUpdate(qry);
74 st.close();
75 }
76 catch (SQLException e)
77 {
78 connect();
79 e.printStackTrace();
80 }
81 }
82 }
83
84 private static boolean hasConnection()
85 {
86 if (con != null) {
87 return true;
88 }
89 return false;
90 }
91
92 public static ResultSet getResult(String qry)
93 {
94 if (hasConnection())
95 {
96 ResultSet rs = null;
97 try
98 {
99 Statement st = con.createStatement();
100 rs = st.executeQuery(qry);
101 }
102 catch (SQLException e)
103 {
104 connect();
105 e.printStackTrace();
106 }
107 return rs;
108 }
109 return null;
110 }
111
112 public static void createTables()
113 {
114 if (hasConnection()) {
115 try
116 {
117 con.createStatement().executeUpdate(
118 "CREATE TABLE IF NOT EXISTS " +
119 Main.stg.getString("database") +
120 "(UUID VARCHAR(100),Coins int)");
121 }
122 catch (SQLException e)
123 {
124 e.printStackTrace();
125 }
126 }
127 }
128}