Skip to content

Instantly share code, notes, and snippets.

@Nabid
Last active July 18, 2022 16:07
Show Gist options
  • Save Nabid/5deffdb2fdfcbbfe702a to your computer and use it in GitHub Desktop.
Save Nabid/5deffdb2fdfcbbfe702a to your computer and use it in GitHub Desktop.
MySQL helper class for Java. MySQL JDBC driver connection Java class example.
/*
Assuming that you have proper MySQL JDBC driver:
How to use this class?
1. Create new object
DBHelper db = new DBHelper();
2. Open connection
db.open();
3. Call corresponding method
db.test();
4. Close connection
db.close;
+ jdbc driver can be found at: http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author nabid
*/
public class DBHelper {
// JDBC driver name and database URL
private final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private final String DB_URL = "jdbc:mysql://localhost/database_name";
// Database credentials
private static final String USER = "username";
private static final String PASS = "password";
private Connection conn = null;
private Statement stmt = null;
public DBHelper() {
//STEP 2: Register JDBC driver
try {
Class.forName(JDBC_DRIVER);
} catch(Exception e) {
e.printStackTrace();
}
}
public void open() {
try {
//System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER,PASS);
//System.out.println("Creating statement...");
stmt = conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void close() {
try {
stmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void test() {
try {
String sql;
sql = "SELECT * FROM table_name";
ResultSet rs = stmt.executeQuery(sql); // DML
// stmt.executeUpdate(sql); // DDL
//STEP 5: Extract data from result set
while(rs.next()){
//Display values
System.out.print(rs.getString(1));
System.out.print(rs.getString(2));
}
//STEP 6: Clean-up environment
rs.close();
} catch (SQLException ex) {
Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@jahanmal
Copy link

Tanks brooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo

@hassannaghibi
Copy link

Thanks, buddy.
It's great.

@Nabid
Copy link
Author

Nabid commented Feb 10, 2020

Thank you! I think need replace:
Class.forName("JDBC_DRIVER");
to
Class.forName(JDBC_DRIVER);

Thanks, updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment