Database.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /*
  2. * Copyright (C) 2012 Matt 'The Yeti' Burnett & mcMMO Development
  3. * Copyright (C) 2010-2011 'nossr50'
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. package com.gmail.nossr50;
  19. import java.sql.Connection;
  20. import java.sql.DriverManager;
  21. import java.sql.ResultSet;
  22. import java.sql.SQLException;
  23. import java.sql.PreparedStatement;
  24. import java.util.HashMap;
  25. import java.util.ArrayList;
  26. import java.util.Properties;
  27. import com.gmail.nossr50.config.LoadProperties;
  28. import com.gmail.nossr50.datatypes.DatabaseUpdate;
  29. public class Database {
  30. private mcMMO plugin;
  31. private String connectionString = "jdbc:mysql://" + LoadProperties.MySQLserverName + ":" + LoadProperties.MySQLport + "/" + LoadProperties.MySQLdbName + "?user=" + LoadProperties.MySQLuserName + "&password=" + LoadProperties.MySQLdbPass;
  32. private boolean isConnected;
  33. private Connection conn = null;
  34. public Database(mcMMO instance) {
  35. connect(); //Connect to MySQL
  36. this.plugin = instance;
  37. // Load the driver instance
  38. try {
  39. Class.forName("com.mysql.jdbc.Driver");
  40. DriverManager.getConnection(connectionString);
  41. }
  42. catch (ClassNotFoundException e) {
  43. plugin.getServer().getLogger().warning(e.getLocalizedMessage());
  44. }
  45. catch (SQLException ex) {
  46. plugin.getServer().getLogger().warning(ex.getLocalizedMessage());
  47. printErrors(ex);
  48. }
  49. }
  50. /**
  51. * Attempt to connect to the mySQL database.
  52. */
  53. public void connect() {
  54. try {
  55. System.out.println("[mcMMO] Attempting connection to MySQL...");
  56. Properties conProperties = new Properties();
  57. conProperties.put("autoReconnect", "true");
  58. conProperties.put("maxReconnects", "3");
  59. conn = DriverManager.getConnection(connectionString, conProperties);
  60. isConnected = true;
  61. System.out.println("[mcMMO] Connection to MySQL established!");
  62. }
  63. catch (SQLException ex) {
  64. isConnected = false;
  65. ex.printStackTrace();
  66. printErrors(ex);
  67. }
  68. }
  69. /**
  70. * Attempt to create the database structure.
  71. */
  72. public void createStructure() {
  73. write("CREATE TABLE IF NOT EXISTS `" + LoadProperties.MySQLtablePrefix + "huds` (`user_id` int(10) unsigned NOT NULL,"
  74. + "`hudtype` varchar(50) NOT NULL DEFAULT '',"
  75. + "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  76. write("CREATE TABLE IF NOT EXISTS `" + LoadProperties.MySQLtablePrefix + "users` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
  77. + "`user` varchar(40) NOT NULL,"
  78. + "`lastlogin` int(32) unsigned NOT NULL,"
  79. + "`party` varchar(100) NOT NULL DEFAULT '',"
  80. + "PRIMARY KEY (`id`),"
  81. + "UNIQUE KEY `user` (`user`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
  82. write("CREATE TABLE IF NOT EXISTS `" + LoadProperties.MySQLtablePrefix + "cooldowns` (`user_id` int(10) unsigned NOT NULL,"
  83. + "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
  84. + "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
  85. + "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
  86. + "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
  87. + "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
  88. + "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
  89. + "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
  90. + "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
  91. + "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
  92. + "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
  93. + "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
  94. + "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
  95. + "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  96. write("CREATE TABLE IF NOT EXISTS `" + LoadProperties.MySQLtablePrefix + "skills` (`user_id` int(10) unsigned NOT NULL,"
  97. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  98. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  99. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  100. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  101. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  102. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  103. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  104. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  105. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  106. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  107. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  108. + "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  109. write("CREATE TABLE IF NOT EXISTS `" + LoadProperties.MySQLtablePrefix + "experience` (`user_id` int(10) unsigned NOT NULL,"
  110. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  111. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  112. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  113. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  114. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  115. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  116. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  117. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  118. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  119. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  120. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  121. + "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  122. write("DROP TABLE IF EXISTS `"+LoadProperties.MySQLtablePrefix+"skills2`");
  123. write("DROP TABLE IF EXISTS `"+LoadProperties.MySQLtablePrefix+"experience2`");
  124. write("DROP TABLE IF EXISTS `"+LoadProperties.MySQLtablePrefix+"spawn`");
  125. checkDatabaseStructure(DatabaseUpdate.FISHING);
  126. checkDatabaseStructure(DatabaseUpdate.BLAST_MINING);
  127. }
  128. /**
  129. * Check database structure for missing values.
  130. *
  131. * @param update Type of data to check updates for
  132. */
  133. public void checkDatabaseStructure(DatabaseUpdate update) {
  134. String sql = null;
  135. ResultSet rs = null;
  136. HashMap<Integer, ArrayList<String>> Rows = new HashMap<Integer, ArrayList<String>>();
  137. switch (update) {
  138. case BLAST_MINING:
  139. sql = "SELECT * FROM `"+LoadProperties.MySQLtablePrefix+"cooldowns` ORDER BY `"+LoadProperties.MySQLtablePrefix+"cooldowns`.`blast_mining` ASC LIMIT 0 , 30";
  140. break;
  141. case FISHING:
  142. sql = "SELECT * FROM `"+LoadProperties.MySQLtablePrefix+"experience` ORDER BY `"+LoadProperties.MySQLtablePrefix+"experience`.`fishing` ASC LIMIT 0 , 30";
  143. break;
  144. default:
  145. break;
  146. }
  147. try {
  148. PreparedStatement stmt = conn.prepareStatement(sql);
  149. if (stmt.executeQuery() != null) {
  150. stmt.executeQuery();
  151. rs = stmt.getResultSet();
  152. while (rs.next()) {
  153. ArrayList<String> Col = new ArrayList<String>();
  154. for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
  155. Col.add(rs.getString(i));
  156. }
  157. Rows.put(rs.getRow(), Col);
  158. }
  159. }
  160. }
  161. catch (SQLException ex) {
  162. if (update.equals(DatabaseUpdate.BLAST_MINING)) {
  163. System.out.println("Updating mcMMO MySQL tables for Blast Mining...");
  164. write("ALTER TABLE `"+LoadProperties.MySQLtablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0' ;");
  165. }
  166. else if (update.equals(DatabaseUpdate.FISHING)) {
  167. System.out.println("Updating mcMMO MySQL tables for Fishing...");
  168. write("ALTER TABLE `"+LoadProperties.MySQLtablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
  169. write("ALTER TABLE `"+LoadProperties.MySQLtablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
  170. }
  171. }
  172. }
  173. /**
  174. * Attempt to write the SQL query.
  175. *
  176. * @param sql Query to write.
  177. * @return true if the query was successfully written, false otherwise.
  178. */
  179. public boolean write(String sql) {
  180. if (conn != null) {
  181. try {
  182. PreparedStatement stmt = conn.prepareStatement(sql);
  183. stmt.executeUpdate();
  184. return true;
  185. }
  186. catch (SQLException ex) {
  187. printErrors(ex);
  188. return false;
  189. }
  190. }
  191. else {
  192. isConnected = false;
  193. connect(); //Attempt to reconnect
  194. if (isConnected) {
  195. write(sql); //Try the same operation again now that we are connected
  196. }
  197. else {
  198. System.out.println("[mcMMO] Unable to connect to MySQL! Make sure the SQL server is online!");
  199. }
  200. }
  201. return false;
  202. }
  203. /**
  204. * Get the Integer. Only return first row / first field.
  205. *
  206. * @param sql SQL query to execute
  207. * @return the value in the first row / first field
  208. */
  209. public Integer getInt(String sql) {
  210. ResultSet rs = null;
  211. Integer result = 0;
  212. if (conn != null) {
  213. try {
  214. PreparedStatement stmt = conn.prepareStatement(sql);
  215. stmt = conn.prepareStatement(sql);
  216. if (stmt.executeQuery() != null) {
  217. stmt.executeQuery();
  218. rs = stmt.getResultSet();
  219. if (rs.next()) {
  220. result = rs.getInt(1);
  221. }
  222. else {
  223. result = 0;
  224. }
  225. }
  226. }
  227. catch (SQLException ex) {
  228. printErrors(ex);
  229. }
  230. }
  231. else {
  232. isConnected = false;
  233. connect(); //Attempt to reconnect
  234. if (isConnected) {
  235. getInt(sql); //Try the same operation again now that we are connected
  236. }
  237. else {
  238. System.out.println("[mcMMO] Unable to connect to MySQL! Make sure the SQL server is online!");
  239. }
  240. }
  241. return result;
  242. }
  243. /**
  244. * Read SQL query.
  245. *
  246. * @param sql SQL query to read
  247. * @return the rows in this SQL query
  248. */
  249. public HashMap<Integer, ArrayList<String>> read(String sql) {
  250. ResultSet rs = null;
  251. HashMap<Integer, ArrayList<String>> Rows = new HashMap<Integer, ArrayList<String>>();
  252. if (conn != null) {
  253. try {
  254. PreparedStatement stmt = conn.prepareStatement(sql);
  255. if (stmt.executeQuery() != null) {
  256. stmt.executeQuery();
  257. rs = stmt.getResultSet();
  258. while (rs.next()) {
  259. ArrayList<String> Col = new ArrayList<String>();
  260. for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
  261. Col.add(rs.getString(i));
  262. }
  263. Rows.put(rs.getRow(), Col);
  264. }
  265. }
  266. }
  267. catch (SQLException ex) {
  268. printErrors(ex);
  269. }
  270. }
  271. else {
  272. isConnected = false;
  273. connect(); //Attempt to reconnect
  274. if (isConnected) {
  275. read(sql); //Attempt the same operation again now that we are connected
  276. }
  277. else {
  278. System.out.println("[mcMMO] Unable to connect to MySQL! Make sure the SQL server is online!");
  279. }
  280. }
  281. return Rows;
  282. }
  283. private static void printErrors(SQLException ex) {
  284. System.out.println("SQLException: " + ex.getMessage());
  285. System.out.println("SQLState: " + ex.getSQLState());
  286. System.out.println("VendorError: " + ex.getErrorCode());
  287. }
  288. }