Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package de.cynfos.mysqlapi;
- import java.io.File;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import org.bukkit.configuration.file.FileConfiguration;
- public class MySQL {
- private int port;
- private String host, user, password, database;
- private Connection conn;
- public MySQL() {
- File file = new File("plugins/MySQL-API/", "config.yml");
- FileConfiguration cfg = this.plugin.getConfig();
- String db = "database.";
- cfg.addDefault(db + "host", "localhost");
- cfg.addDefault(db + "port", 3306);
- cfg.addDefault(db + "user", "root");
- cfg.addDefault(db + "password", "password");
- cfg.addDefault(db + "database", "database");
- cfg.options().copyDefaults(true);
- try {
- cfg.save(file);
- } catch (IOException e) {
- e.printStackTrace();
- }
- this.host = cfg.getString(db + "host");
- this.port = cfg.getInt(db + "port");
- this.user = cfg.getString(db + "user");
- this.password = cfg.getString(db + "password");
- this.database = cfg.getString(db + "database");
- this.openConnection();
- }
- private Connection openConnection() {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- Connection conn = DriverManager.getConnection("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database, this.user, this.password);
- this.conn = conn;
- return conn;
- } catch (SQLException | ClassNotFoundException e) {
- e.printStackTrace();
- }
- return null;
- }
- public Connection getConnection() {
- return this.conn;
- }
- public boolean hasConnection() {
- try {
- return this.conn != null || this.conn.isValid(1);
- } catch (SQLException e) {
- return false;
- }
- }
- public void queryUpdate(String query) {
- Connection conn = this.conn;
- PreparedStatement st = null;
- try {
- st = conn.prepareStatement(query);
- st.executeUpdate();
- } catch (SQLException e) {
- System.err.println("[MySQL] Failed to send update '" + query + "' (" + e.getMessage() + ")");
- } finally {
- this.closeRessources(null, st);
- }
- }
- public void closeRessources(ResultSet rs, PreparedStatement st) {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException e) {
- }
- }
- if (st != null) {
- try {
- st.close();
- } catch (SQLException e) {
- }
- }
- }
- public void closeConnection() {
- try {
- this.conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- this.conn = null;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement