lam melakukan koneksi database dari java ke MySQL menggunakan JDBC, maka kita harus lebih dulu menginstall JDBC driver dan MySQL.
contoh program koneksi database :
public void koneksiDatabase() {
try {
Class.forName("com.mysql.jdbc.Driver");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Sukses Driver JDBC ditemukan ....");
try {
String url = "jdbc:mysql://localhost:3306/Database05?user=fatwati&password=ternate";
konek = DriverManager.getConnection(url);
System.out.println("Sukses Koneksi ....");
String url = "jdbc:odbc:DNSGL";
String user = "";
String pass = "";
konek = DriverManager.getConnection(url, user, pass);
System.out.println("Sukses Koneksi ....") ; }
catch (SQLException se) {
System.out.println("Koneksi Gagal = " + se);
System.exit(0); }
}
}
catch (ClassNotFoundException cnfe) {
System.out.println("Class tidak ditemukan.. Error : " + cnfe);
System.exit(0);
}
}
public void tampilDataKeTabel() {
hapusTabel();
try {
String sql = "Select * from tbuser";
Statement stat = konek.createStatement();
ResultSet set = stat.executeQuery(sql);
while (set.next()) {
String kode = set.getString("UserId");
String nama = set.getString("nama");
String alamat = set.getString("Password");
String kelas = set.getString("Otoritas");
String[] data = {kode, nama, alamat, kelas};
tabMode.addRow(data); }
}
catch (Exception e) {}
}