Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.dondays.api.database;
- import ru.dondays.api.Main;
- import java.sql.*;
- public class SQLConnection
- implements DatabaseConnector {
- private Connection connection;
- private String host;
- private String database;
- private String user;
- private String password;
- private SQLConnection(String host, String user, String password) {
- this.host = host;
- this.user = user;
- this.password = password;
- }
- public SQLConnection(String host, String user, String password, String database) {
- this(host, user, password);
- this.database = database;
- }
- public Connection getConnection() throws SQLException {
- if(this.connection == null || this.connection.isClosed()) {
- this.connect();
- }
- return this.connection;
- }
- public void connect() throws SQLException {
- try {
- this.connection = DriverManager.getConnection("JDBC:mysql://" + this.host + ":3306/" + this.database + "?useUnicode=true&characterEncoding=UTF-8&" + "user=" + this.user + "&password=" + this.password);
- } catch(SQLException var2) {
- Main.getInstance().getLogger().info("При соединении с базой данных (" + this.host + ", " + this.database + ") произошла ошибка - " + var2.getMessage());
- var2.printStackTrace();
- }
- }
- public void execute(String sql) throws SQLException {
- Statement statement = null;
- try {
- statement = this.getConnection().createStatement();
- statement.executeUpdate(sql);
- } finally {
- if(statement != null) {
- statement.close();
- }
- }
- }
- public ResultSet executeQuery(String sql) throws SQLException {
- Statement statement = null;
- ResultSet rs = null;
- try {
- statement = this.getConnection().createStatement();
- rs = statement.executeQuery(sql);
- } finally {
- if(rs != null) {
- while(rs.isClosed()) {
- if(statement != null) statement.close();
- }
- }
- }
- return rs;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement