Java Connect MySQL

Posted by Mr | 3:35 AM | , | 1 comments »

Berikut contoh program Java yang menampilkan data dari Database MySQL..

Class COnnect:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package MySQL;
import java.sql.*;
/**
*
* @author todorov
*/
public class Conn {
static Connection kon = null;

//get konek here
public static Connection getConnect()
{
// Test Driver
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
System.out.print(e);
}
// Test Connection
try{
kon = DriverManager.getConnection("jdbc:mysql://localhost:3306/penjualan", "root","root");
//System.out.print("Koneksi berhasil");
}catch(Exception e){
System.out.print(e);
}
return kon;
}

//Close Connection
public static void disConnect()
{
try{
kon.close();
}catch(Exception ex)
{
System.out.print(ex);
}
}
}

Class View

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package MySQL;
import java.io.*;
import java.sql.*;
import java.awt.*;
import javax.swing.*;
/**
*
* @author todorov
*/
public class ViewKonsumen {
static Connection conn = Conn.getConnect();
// Void Tampil()
public static void main()
{
String hasil = "KODE|NAMA|ALAMAT|KOTA|PHONE|EMAIL\n";
// Query Here
try {
Statement sql = conn.createStatement();
ResultSet rs = null;
rs = sql.executeQuery("SELECT * FROM KONSUMEN");

//Show Query
try{
while(rs.next()){
hasil = hasil + rs.getString(1) +"|"+ rs.getString(2)+"|"
+ rs.getString(3)+"|"+ rs.getString(4)+"|"+ rs.getString(5)
+"|"+ rs.getString(6) + "\n";
}
}
catch(Exception ex){
System.err.println("Kesalahan:" + ex);
System.exit(1);
}
}
catch (Exception ex){
System.out.println("Kesalahan : " + ex);
}
JOptionPane.showMessageDialog(null,hasil,"Data Konsumen",
JOptionPane.INFORMATION_MESSAGE);
}
}

Class Main.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package MySQL;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
/**
*
* @author todorov
*/
public class Main {
private static byte iPilih = 6;
public static String sPilih;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Konsumen kons = new Konsumen();
while(iPilih!=5) {
try{
iPilih = Byte.parseByte(JOptionPane.showInputDialog(null,
"Masukkan pilihan : " +
"\n 1. Tampil Data \n 2. Tambah Data " +
"\n 3. Koreksi Data \n 4. Hapus Data \n 5. Keluar"));
} catch(Exception e){
JOptionPane.showMessageDialog(null,"Pilihan",
"Pilihan Anda Salah !!!"
,JOptionPane.INFORMATION_MESSAGE);
}
switch(iPilih){

case 1 : ViewKonsumen view = new ViewKonsumen();
view.main();
break;

}
};
}

}

1 comments

  1. Mr // December 22, 2008 at 9:09 PM  

    test Komment