Skip to content

Instantly share code, notes, and snippets.

@imamhidayat92
Last active December 16, 2015 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imamhidayat92/5418582 to your computer and use it in GitHub Desktop.
Save imamhidayat92/5418582 to your computer and use it in GitHub Desktop.
/*
Author: Imam Hidayat (mokhamad.imam[at]students.paramadina.ac.id)
Universitas Paramadina
Source: https://gist.github.com/imamhidayat92/5418582
This helper class can be used to simplify query execution using MySQL Database in Java.
*/
import java.sql.*;
import javax.swing.JOptionPane;
public class MySQLConnector {
/* Class Configurations */
public static final String DB_NAME = "dbname";
public static final String DB_HOST = "localhost";
public static final int DB_PORT = 3306;
public static final String DB_USER = "dbuser";
public static final String DB_PASSWORD = "dbpassword";
public static Connection conn = null;
public static Statement stat = null;
public static void connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://" + DB_HOST + ":" + String.valueOf(DB_PORT) + "/" + DB_NAME, DB_USER, DB_PASSWORD);
stat = conn.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static ResultSet executeQuery(String query) throws SQLException {
connect();
return stat.executeQuery(query);
}
public static int executeUpdate(String query) throws SQLException {
connect();
return stat.executeUpdate(query);
}
public static void close() {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment