Selasa, 09 September 2008

access dbms using jdbc

java have jdbc API to connect apps with rdbms. if we wanna use jdbc to connect dbms, there are many step that we must do it.
1. load the driver (jdbc driver must be specific with which rdbms we use)
2. open connection
3. create statement
4. execute statement
5. getting the result
6. close connection

example retrieve data
i use MySQL in this tutorial. i have database "tryout" and i was create table "mahasiswa"



package kpts;
import java.sql.*;

public class TesJDBC {

// Deklarasi atribut
Connection con = null;
ResultSet
rs = null;
Statement
stmt = null;
String
strSQL = "select * from mahasiswa order by nim";

// Konstruktor
public TesJDBC(){}

public void makeConnection() throws Exception {
Class.forName(
"com.mysql.jdbc.Driver");
con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/modul","root","");
}

public boolean getMahasiswa() throws Exception {
stmt = con.createStatement();
rs = stmt.executeQuery(strSQL);
return (rs != null);
}

public boolean getNextMahasiswa() throws Exception {
return rs.next(); //mengambil data pada row berikutnya
}

public String getColumn(String inCol) throws Exception {
return rs.getString(inCol); //mengambil data berdasarkan kolom
}
public void takeDown() throws Exception {
stmt.close(); //menutup statement
con.close(); //menutup koneksi
}
}

public static void main(String[] args) {

TesJDBC a = new TesJDBC();
try {
a.makeConnection();
if (a.getMahasiswa()) {
while (a.getNextMahasiswa()){
String nim = a.getColumn(
"nim");
String nama = a.getColumn(
"nama");
String alamat = a.getColumn(
"kelas");
String kelas = a.getColumn(
"kelas");
System.
out.print(nim+" "+nama+" "+alamat+" "+kelas);
System.
out.println();
}
}a.takeDown();

} catch (Exception e) {
e.printStackTrace();
}
}
}

live blogging in touring lab mabim

now i being presentation about my lab to mabimer's ittelkom
i try to explain about OpenSource especially java technology
cause core my lab was developing apps using java tech

i hope there are many mabimer's will appreciate about my presentation
so my lab will have a lot of members and we can build some products

justin start blogging

i try to force my self learn to share my acknowledgments

-jst-