JDBC - Make a connection Java and MySQL



On this occasion I
will share about how to make a connection with MySQL Java. What we need here is NetBeans as the IDE, which would free version of what happened to me using NetBeans 7.0, but that we also need the XAMPP for MySQL database. Immediately, I explain codingnya below:

1. First we make a Java class in NetBeans with the name "Koneksi.java"
2. Then type in the script as below
:
-------------------------------------------------------------------------------
public class Koneksi {
Connection con;
String driver,url,user,pass;

public Koneksi() {
this.driver="com.mysql.jdbc.Driver";
this.url="jdbc:mysql://localhost:3306/kuliah";
this.user="root";
this.pass="root";
}

public Koneksi(Connection con, String driver, String url, String user, String pass) {
this.con = con;
this.driver = driver;
this.url = url;
this.user = user;
this.pass = pass;
}

public void BukaKoneksi(){
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url,user,pass);
} catch (SQLException ex) {
Logger.getLogger(Koneksi.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(Koneksi.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Koneksi.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Koneksi.class.getName()).log(Level.SEVERE, null, ex);
}
}

public Connection getCon() {
return con;
}

public void setCon(Connection con) {
this.con = con;
}
}
-------------------------------------------------------------------------------

0 komentar:

Posting Komentar