MySQL CRUD in Java
This code is originally writen by Angelo Rodrigues which written in PHP version. I have rewrite the code in JAVA version and already used for many of my application.
In this tutorial, I only explain how to using this class. Please read angelo’s post if you don’t understand how it work. Here is the explanation:
Function Connect & Disconnect:
public class Database {
private String host = “localhost”;
private String user = some_user;
private String pass = some_password;
private String dbase = some_database;
private Statement stmt = null;
private ResultSet rs = null;
private String url = “jdbc:mysql://” +host+ “:3306/”;
private Connection con = null;public Database() throws SQLException{
try {
Class.forName(“com.mysql.jdbc.Driver”);
con = DriverManager.getConnection(url+dbase,user, pass);
stmt = con.createStatement();
}
catch(ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
}public void disconnect() {
try {
if(rs != null) {
rs.close();
}
if(stmt != null) {
stmt.close();
}
if(con != null) {
con.close();
}
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
As you seen, the class will try connect to database when the class loaded. Simply to use syntax like this
public void testConnect() {
Database db = null;
try {
db = new Database()
} catch(Exception ex) {
System.out.println(ex.getMessage());
} finally {
db.disconnect();
}
}
Regard,
Febri
To be continue…..
Download source here
Comment from free advertising
Time August 13, 2011 at 12:33 pm
Some truly nice and useful information on this site, likewise I believe the pattern has good features.