Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package core.database;
- import java.sql.*;
- public class MySQL {
- private static Class driverClass;
- private static Connection connection;
- private static Statement statement;
- public static boolean Open(String host, String database, String username, String password) {
- try {
- driverClass = Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection("jdbc:mysql://" + host + "/" + database + "?" +
- "user=" + username + "&password=" + password);
- statement = connection.createStatement();
- } catch(Exception e) {
- e.printStackTrace();
- return false;
- } finally {
- if(connection != null)
- Close();
- }
- return true;
- }
- public static void Close() {
- try {
- connection.close();
- System.out.println("Disconnected from mysql");
- } catch (Exception e) { }
- }
- public static void Query(String query) {
- try {
- statement.executeUpdate(query);
- } catch(SQLException sqle) {
- sqle.printStackTrace();
- }
- }
- public static <T> void Insert(String table, String[] keys, T[] values) {
- String execute;
- try {
- execute = "INSERT INTO " + table;
- if(keys.length > 0) {
- execute += "(";
- boolean firstTime = true;
- for(String key:keys) {
- if(!firstTime)
- execute += ",";
- execute += key;
- firstTime = false;
- }
- execute += ")";
- }
- execute += " VALUES(";
- boolean firstTime = true;
- for(T value:values) {
- if(!firstTime)
- execute += ",";
- execute += "\'" + value + "\'";
- firstTime = false;
- }
- execute += ")";
- statement.executeUpdate(execute);
- } catch(SQLException sqle) {
- sqle.printStackTrace();
- }
- }
- public static String[][] Read(String table, String[] columns, String[] conditions, String[] condition_values, int limit) {
- String execute = "";
- try {
- execute = "SELECT ";
- boolean firstTime = true;
- for(String column:columns) {
- if(!firstTime)
- execute += ",";
- execute += column;
- firstTime = false;
- }
- execute += " FROM " + table;
- if(conditions != null) {
- execute += " WHERE ";
- int c = 0;
- boolean fTime = true;
- for(String condition:conditions) {
- if(!fTime)
- execute += ",";
- execute += condition + " = '" + condition_values[c] + "'";
- c++;
- fTime = false;
- }
- }
- if(limit > 0) {
- execute += " LIMIT " + limit;
- }
- int x = 0;
- ResultSet resultSet = statement.executeQuery(execute);
- while(resultSet.next()) { x++; }
- String[][] results = new String[x][columns.length];
- ResultSet rs = statement.executeQuery(execute);
- x = 0;
- while(rs.next()) {
- for(int y = 0; y < columns.length; y++) {
- results[x][y] = rs.getString(y);
- }
- x++;
- }
- return results;
- } catch(Exception e) {
- e.printStackTrace();
- return new String[][]{};
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement