Guest User

Untitled

a guest
May 16th, 2018
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.59 KB | None | 0 0
  1. package lib.JesiKat.SQL;
  2.  
  3.  
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9. import java.util.ArrayList;
  10. import java.util.Arrays;
  11. import java.util.Collections;
  12. import java.util.List;
  13.  
  14. /**
  15. * @author Jesika(Kaitlyn) Tremaine aka JesiKat
  16. *
  17. * MySQLConnection.
  18. * This class is a simple database connector with the basic useful methods such as getting the number of rows in a table,
  19. * the names of columns in the table, etc.
  20. */
  21. public class MySQLConnection {
  22. /*The host for the database, the username for the database, and the password*/
  23. private final String dbUrl, dbUsername, dbPassword;
  24.  
  25. /*The connection object*/
  26. private Connection databaseConnection;
  27.  
  28. /**
  29. *
  30. * @param host The host of the database server
  31. * @param port The port that the server is on
  32. * @param database The name of the database to connect to. If left as null, it will connect to the server without
  33. * using a database
  34. * @param username The username for the database.
  35. * @param password The password for the database
  36. * @return The resulting MySQLConnection. Returns null if there was an error.
  37. */
  38. public static MySQLConnection newJDBCConnection(String host, int port, String database, String username, String password) {
  39. try {
  40. return new MySQLConnection(host, port, database, username, password);
  41. } catch (Exception e) {
  42. return null;
  43. }
  44. }
  45. /**
  46. *
  47. * @param host The host of the database server
  48. * @param port The port that the server is on
  49. * @param username The username for the database
  50. * @param password The password for the database
  51. * @return The resulting MySQLConnection. Returns null if there was an error
  52. */
  53. public static MySQLConnection newJDBCConnection(String host, int port, String username, String password) {
  54. return newJDBCConnection(host, port, "", username, password);
  55. }
  56. /**
  57. *
  58. * @param host The host of the database server
  59. * @param username The username for the database.
  60. * @param password The password for the database
  61. * @return The resulting MySQLConnection. Returns null if there was an error.
  62. */
  63. public static MySQLConnection newJDBCConnection(String host, String username, String password) {
  64. return newJDBCConnection(host, 3306, "", username, password);
  65. }
  66.  
  67. public MySQLConnection(String host, int port, String database, String username, String password) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  68. this.dbUrl = host + ":" + port + "/" + database;
  69. this.dbUsername = username;
  70. this.dbPassword = password;
  71. Class.forName("com.mysql.jdbc.Driver").newInstance();
  72. }
  73.  
  74. /**
  75. * @return True if the connection was made successfully, false if otherwise.
  76. */
  77. public boolean connect() { return connect(false); }
  78. /**
  79. * @param printerror If this is true, this method will print an error if there is one and return false
  80. * @return True if the connection was made successfully, false if otherwise.
  81. */
  82. public boolean connect(boolean printerror) {
  83. try {
  84. this.databaseConnection = DriverManager.getConnection("jdbc:mysql://" + this.dbUrl, this.dbUsername, this.dbPassword);
  85. if (this.databaseConnection==null) return false;
  86. return true;
  87. } catch (SQLException e) {
  88. if (printerror) e.printStackTrace();
  89. return false;
  90. }
  91. }
  92.  
  93. /**
  94. * @return True if the disconnect was successful, false if otherwise.
  95. */
  96. public boolean disconnect() { return disconnect(false); }
  97. /**
  98. * @param printerror If this is true, this method will print an error if there is one and return false.
  99. * @return True if the disconnect was successful, false if otherwise.
  100. */
  101. public boolean disconnect(boolean printerror) {
  102. try {
  103. this.databaseConnection.close();
  104. return true;
  105. } catch (SQLException e) {
  106. if (printerror) e.printStackTrace();
  107. return false;
  108. }
  109. }
  110.  
  111. /**
  112. * @param query The Query to send to the SQL server.
  113. * @param modifies If the Query modifies the database, set this to true. If not, set this to false
  114. * @return If {@value modifies} is true, returns a valid ResultSet obtained from the Query. If {@value modifies} is false, returns null.
  115. * @throws SQLException if the Query had an error or there was not a valid connection.
  116. */
  117. public ResultSet executeQuery(String query, boolean modifies) throws SQLException {
  118. Statement statement = this.databaseConnection.createStatement();
  119. if (modifies) {
  120. statement.execute(query);
  121. return null;
  122. } else {
  123. return statement.executeQuery(query);
  124. }
  125. }
  126.  
  127. /**
  128. * @param database The database to check for existence.
  129. * @return true if the database exists, false if there was an error or the database doesn't exist.
  130. *
  131. * This method looks through the information schema that comes with a MySQL installation and
  132. * checks to see if a certain database exists.
  133. */
  134. public boolean databaseExists(String database) {
  135. String format = "SELECT * FROM `information_schema`.`schemata` WHERE `SCHEMA_NAME` = '$DB' ;";
  136. try {
  137. return this.executeQuery(format.replace("$DB", database), false).first();
  138. } catch (SQLException e) {
  139. return false;
  140. }
  141. }
  142.  
  143. /**
  144. * @param database The database to check for the table in.
  145. * @param table The table to check for existence.
  146. * @return true if the table exists, false if there was an error or the database doesn't exist.
  147. *
  148. * This method looks through the information schema that comes with a MySQL installation and checks
  149. * if a certain table exists within a database.
  150. */
  151. public boolean tableExists(String database, String table) {
  152. String format = "SELECT * FROM `information_schema`.`TABLES` WHERE TABLE_SCHEMA = '$DB' && TABLE_NAME = '$TABLE';";
  153. try {
  154. return this.databaseConnection.createStatement().executeQuery(format.replace("$DB", database).replace("$TABLE", table)).first();
  155. } catch (SQLException e) {
  156. return false;
  157. }
  158. }
  159.  
  160. /**
  161. * @param database The database the table is in.
  162. * @param table The table to get the row count from.
  163. * @return the number of rows in the table.
  164. *
  165. * This method loops through all rows and returns the row count.
  166. */
  167. public int getRowCount(String database, String table) {
  168. String format = "SELECT * FROM `$DB`.`$TABLE`;";
  169. int rows = 0;
  170. try {
  171. ResultSet set = executeQuery(format.replace("$DB", database).replace("$TABLE", table), false);
  172. while (set.next()) { rows++; }
  173. } catch (SQLException e) {
  174. return 0;
  175. }
  176. return rows;
  177. }
  178.  
  179. /**
  180. * @param database The database the table is in.
  181. * @param table The table to get the columns from.
  182. * @return A String array containing the names of all the columns from the table in the order they are in in the table.
  183. * @throws SQLException
  184. *
  185. * This method loops through all columns of a table within a database and adds their name to an array, then returns the
  186. * array.
  187. */
  188. public String[] getColumns(String database, String table) throws SQLException {
  189. String format = "SELECT * FROM `$DB`.`$TABLE`;";
  190. ResultSet set = executeQuery(format.replace("$DB", database).replace("$TABLE", table), false);
  191. int count = set.getMetaData().getColumnCount();
  192. ArrayList<String> columns = new ArrayList<String>();
  193. for (int i = 1; i<=count; i++) {
  194. columns.add(set.getMetaData().getColumnName(i));
  195. }
  196. return columns.toArray(new String[columns.size()]);
  197. }
  198.  
  199. /**
  200. * @param database The database to get the tables from.
  201. * @return A String array containing all of the tables in the database in alphabetical order.
  202. * @throws SQLException
  203. */
  204. public String[] getTables(String database) throws SQLException {
  205. String format = "SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE TABLE_SCHEMA='$DB';";
  206. ResultSet set = executeQuery(format.replace("$DB", database), false);
  207. ArrayList<String> tables = new ArrayList<String>();
  208. while (set.next()) {
  209. tables.add(set.getString(1));
  210. }
  211. List<String> sorted = Arrays.asList(tables.toArray(new String[tables.size()]));
  212. Collections.sort(sorted, String.CASE_INSENSITIVE_ORDER);
  213. return sorted.toArray(new String[tables.size()]);
  214. }
  215.  
  216. /**
  217. * @return A String array of all databases excluding those that are included with the MySQL installation.
  218. * @throws SQLException
  219. */
  220. public String[] getDatabases() throws SQLException { return getDatabases(true); }
  221.  
  222. /**
  223. * @param onlyAdded determines whether or not the method will get all databases or if the method should
  224. * exclude the databases that are included with the MySQL installation.
  225. * @return A String array of all databases. If {@value onlyAdded} is true, returns all databases. If {@value onlyAdded} is false,
  226. * returns all databases excluding those that are included with the MySQL installation.
  227. * @throws SQLException
  228. */
  229. public String[] getDatabases(boolean onlyAdded) throws SQLException {
  230. ResultSet set = executeQuery("SHOW DATABASES;", false);
  231. ArrayList<String> databases = new ArrayList<String>();
  232. while (set.next()) {
  233. String database = set.getString(1);
  234. if (onlyAdded) {
  235. if (!(database.equalsIgnoreCase("information_schema") || database.equalsIgnoreCase("mysql") || database.equalsIgnoreCase("performance_schema"))) {
  236. databases.add(database);
  237. }
  238. } else
  239. databases.add(database);
  240. }
  241. List<String> sorted = Arrays.asList(databases.toArray(new String[databases.size()]));
  242. Collections.sort(sorted, String.CASE_INSENSITIVE_ORDER);
  243. return sorted.toArray(new String[databases.size()]);
  244. }
  245.  
  246. /**
  247. * @return The raw connection that this class uses for database interactions.
  248. */
  249. public Connection getRawConnection() { return this.databaseConnection; }
  250. }
Add Comment
Please, Sign In to add comment