Advertisement
Guest User

Untitled

a guest
Mar 8th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.21 KB | None | 0 0
  1. package julian.mcr.database;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8.  
  9. public class MySQL {
  10.  
  11.     private String HOST = "";
  12.     private String DATABASE = "";
  13.     private String USER = "";
  14.     private String PASSWORD = "";
  15.     private Connection con;
  16.  
  17.     public MySQL(String host, String database, String user, String password) {
  18.         this.HOST = host;
  19.         this.DATABASE = database;
  20.         this.USER = user;
  21.         this.PASSWORD = password;
  22.  
  23.         connect();
  24.     }
  25.  
  26.     public Connection getConnection() {
  27.         return con;
  28.     }
  29.  
  30.     public void connect() {
  31.         try {
  32.             this.con = DriverManager.getConnection(
  33.                     "jdbc:mysql://" + this.HOST + ":3306/" + this.DATABASE + "?autoReconnect=true", this.USER,
  34.                     this.PASSWORD);
  35.             System.out.println("[MySQL] Die Verbindung zur MySQL wurde hergestellt!");
  36.         } catch (SQLException e) {
  37.             System.out.println("[MySQL] Die Verbindung zur MySQL ist fehlgeschlagen! Fehler: " + e.getMessage());
  38.         }
  39.     }
  40.  
  41.     public void close() {
  42.         try {
  43.             if (this.con != null) {
  44.                 this.con.close();
  45.                 System.out.println("[MySQL] Die Verbindung zur MySQL wurde Erfolgreich beendet!");
  46.             }
  47.         } catch (SQLException e) {
  48.             System.out.println("[MySQL] Fehler beim beenden der Verbindung zur MySQL! Fehler: " + e.getMessage());
  49.         }
  50.     }
  51.  
  52.     public boolean isConnected() {
  53.         return this.con != null;
  54.     }
  55.  
  56.     public void update(String qry) {
  57.         try {
  58.             Statement st = this.con.createStatement();
  59.             st.executeUpdate(qry);
  60.             st.close();
  61.         } catch (SQLException e) {
  62.             connect();
  63.             System.err.println(e);
  64.         }
  65.     }
  66.  
  67.     public ResultSet query(String qry) {
  68.         ResultSet rs = null;
  69.         try {
  70.             Statement st = this.con.createStatement();
  71.             rs = st.executeQuery(qry);
  72.         } catch (SQLException e) {
  73.             connect();
  74.             System.err.println(e);
  75.         }
  76.         return rs;
  77.     }
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement