~:Catatan Belajar MazHel:~

Simple Java Connection to mySql

Posted in java by m42h31 on 30 Juli 2008

di posting atas permintaan temenku dan untuk reminder bagi penulis aja lho. tp klu mau ngopi ya sok aja gk dilarang..hehehe..say yes to open source..😀

ok,sebelumnya bikin dulu database “latian” di mySql. dilanjutkan dengan membuat table sederhana “tabel_mhs” field-fieldnya “npm,nama,alamat”. gimana cara buatnya??, saya pikir udh pada jago database jd gk perlu di ajari lagi tho..hehe..

jangan lupa tambahkan setting classpath untuk driver JDBCnya jg ya, atau klu gk mau di pusingkan dengan urusan nyeting classpath, cara paling gampang yaitu dengan mengkopikan driver JDBC ke folder tempat kita bekerja. so its easy right ??
/*
next let’s begin writing the code..

author : m42h31
*/

import java.sql.*;
public class latCon02{

protected Connection con;
protected Statement stt;
protected ResultSet rs;

public latCon02(String host,String db,String usr,String pwd){
try
{
Class.forName(“com.mysql.jdbc.Driver”);
}
catch (ClassNotFoundException ex)
{
System.out.println(“driver not found..!!, “+ex.getMessage());
System.out.println(“”);
}

try
{
con= DriverManager.getConnection(“jdbc:mysql://”+host+”/”+db,usr,pwd);
stt= con.createStatement();
}
catch(SQLException e){
System.out.println(“Connection Failed..!!”+e.getMessage());
System.out.println(“”);
}

}

public void ambilData(String query) throws SQLException{    //select from
rs= stt.executeQuery(query);
}

public void insertData(String query)throws SQLException{ //insert & update
stt.executeUpdate(query);
}
public void view()throws Exception{
System.out.println(“============:MAHASISWA:=============”);
System.out.println(“No    Npm    Nama    Alamat”);
int no=0;
while (rs.next())
{
no++;
System.out.println(no+”\t”+rs.getString(“npm”)+”\t”+rs.getString(“nama”)+”\t”+rs.getString(“alamat”));

}
System.out.println(“====================================”);

}

public static void main (String []args) throws Exception{
latCon02 coba=new latCon02(“localhost”,”latian”,”root”,”123″);
coba.insertData(“insert into tabel_mhs values(‘8106′,’m42h31′,’bandung’)”);
coba.ambilData(“select * from tabel_mhs”);
coba.view();

}
}
the end..

semoga bermanfaat..keep your spirit high!!

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: