Skip to content

Instantly share code, notes, and snippets.

@ivanelianto
Created June 14, 2019 16:04
Show Gist options
  • Save ivanelianto/3b20083b071657d64c9a642d364cfcf0 to your computer and use it in GitHub Desktop.
Save ivanelianto/3b20083b071657d64c9a642d364cfcf0 to your computer and use it in GitHub Desktop.
This file is used to "ISYS6197 Business Application Development" course in BINUS University Kemanggisan to teach about java application and MySQL database
/**
* Author : Ivan F.E. (IV18-1)
* This file is used to "ISYS6197 Business Application Development" course in BINUS University Kemanggisan
* to teach about java application and MySQL database
* 2019
*/
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
public class DbHandler
{
/**
* Server Name
*/
private final static String DB_SERVER = "localhost";
/**
* Server Port
*/
private final static int DB_PORT = 3306;
/**
* Database Name
*/
private final static String DB_NAME = "my_todo";
/**
* Username for Current Selected Database
*/
private final static String DB_USERNAME = "root";
/**
* Password for Current Selected Username
*/
private final static String DB_PASSWORD = "";
/**
* Simple connection string to connect to MySQL database
*/
private static String connectionString =
String.format("jdbc:mysql://%s:%d/%s",
DB_SERVER,
DB_PORT,
DB_NAME);
private static Connection conn;
private DbHandler() {}
/**
* Get connection from metadata that has been provided above.
* @return Opened connection.
*/
private static Connection getConnection()
{
if (conn == null)
{
try
{
DriverManager.registerDriver(new Driver());
conn = (Connection) DriverManager.getConnection(connectionString,
DB_USERNAME,
DB_PASSWORD);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return conn;
}
/**
* Use to retrieve data from MySQL database.
* @param query SELECT Query
* @return Records in ResultSet Data Type
*/
public static ResultSet executeQuery(String query)
{
try (Statement stmt = getConnection().createStatement())
{
return stmt.executeQuery(query);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* Use to execute command for data manipulation in MySQL database.
* @param query INSERT, UPDATE, DELETE Query
*/
public static void execute(String query)
{
try (Statement stmt = getConnection().createStatement())
{
stmt.executeUpdate(query);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment