Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class CoreMySQL {
- private static final String host = "localhost";
- private static final int port = 3306;
- private static final String database = "database";
- private static final String username = "root";
- private static final String password = "root";
- private Connection connection;
- public void openConnection() throws SQLException, ClassNotFoundException {
- if (connection != null && !connection.isClosed()) {
- return;
- }
- synchronized (this) {
- if (connection != null && !connection.isClosed()) {
- return;
- }
- Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true", username, password);
- }
- }
- public ResultSet execute(String s) {
- if (connection == null) {
- try {
- openConnection();
- } catch (ClassNotFoundException | SQLException e) {
- e.printStackTrace();
- }
- }
- try {
- Statement statement = connection.createStatement();
- return statement.executeQuery(s);
- } catch (SQLException e) {
- e.printStackTrace();
- try {
- connection.close();
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- connection = null;
- try {
- openConnection();
- } catch (ClassNotFoundException | SQLException e1) {
- e1.printStackTrace();
- }
- try {
- Statement statement = connection.createStatement();
- return statement.executeQuery(s);
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- }
- return null;
- }
- public int executeUpdate(String string) {
- if (connection == null) {
- try {
- openConnection();
- } catch (ClassNotFoundException | SQLException e) {
- e.printStackTrace();
- }
- }
- try {
- return connection.createStatement().executeUpdate(string);
- } catch (SQLException e) {
- e.printStackTrace();
- try {
- connection.close();
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- connection = null;
- try {
- openConnection();
- } catch (ClassNotFoundException | SQLException e1) {
- e1.printStackTrace();
- }
- try {
- return connection.createStatement().executeUpdate(string);
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement