Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.codemonkey.utils;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class MySQLManager {
- private String host;
- private String port;
- private String database;
- private String user;
- private String password;
- public MySQLManager(String host, String port, String database, String user, String password) {
- this.host = host;
- this.port = port;
- this.database = database;
- this.user = user;
- this.password = password;
- }
- private Connection createConnection() {
- Connection connection;
- try {
- Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, user,
- password);
- return connection;
- } catch (SQLException e) {
- System.out.println("Could not connect to MySQL server! because: " + e.getMessage());
- } catch (ClassNotFoundException e) {
- System.out.println("JDBC Driver not found!");
- }
- return null;
- }
- public ResultSet executeQuery(String query) {
- Connection connection = createConnection();
- Statement statement = null;
- ResultSet set = null;
- try {
- statement = connection.createStatement();
- set = statement.executeQuery(query);
- return set;
- } catch (SQLException e) {
- e.printStackTrace();
- } finally { // Close in order: ResultSet, Statement, Connection.
- try {
- set.close();
- } catch (Exception e) {
- }
- try {
- statement.close();
- } catch (Exception e) {
- }
- try {
- connection.close();
- } catch (Exception e) {
- }
- }
- return null;
- }
- public void executeUpdate(String update) {
- Connection connection = createConnection();
- Statement statement = null;
- try {
- statement = connection.createStatement();
- statement.executeUpdate(update);
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- statement.close();
- } catch (Exception e) {
- }
- try {
- connection.close();
- } catch (Exception e) {
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment