Akses Database MySQL Menggunakan Java NetBean

August 2, 2011 at 5:00 pm Leave a comment

Siapkan databasenya dan Tabelnya

badi@localhost ~]$ mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 32
Server version: 5.1.32 Source distribution

Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.

mysql> use simpeg;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select * from pegawai;
+-------+-----------------------+--------+------+-------+
| NIP | NAMA | ALAMAT | SEKS | AGAMA |
+-------+-----------------------+--------+------+-------+
| 10002 | Endang Susilowati sss | Madiun | P | ISLAM |
| 10003 | Made Saputra | Bali | L | HINDU |
| 10004 | Bejo | Bantul | L | BUDHA |
+-------+-----------------------+--------+------+-------+
3 rows in set (0.00 sec)

 

Membuat Program Koneksi dalam Kelas

 Lihat contoh program berkut :

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jdbc1a;
import java.sql.*;
import javax.swing.*;
/*****************************************
*
* @author badiyanto
* STMIK AKAKOM Yogyakarta
*******************************************/
public class KoneksiDb {
public Connection conn;
public Statement st;
public ResultSet rs;
// Fungsi koneksi
public void koneksi()
{
// memangil fungsi konek() untuk melakukan koneksi
konek("localhost","simpeg","root","");
}
// Program untuk melakukan koneksi
public void konek(String server,String db, String user,String passwd){
System.out.println("Keterangan");
//memanggil driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println(
"Ada kesalahan Driver ODBC tidak barhasil Load");
e.printStackTrace();
return;
}
System.out.println("Mysql JDBC Driver berhasil di Load");
conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://"+
server+":3306/"+db,user,passwd);
} catch (SQLException e) {
System.out.println("Tidak bisa koneksi ke database");
e.printStackTrace();
return;
}
if (conn != null)
System.out.println("Berhasil Koneksi!");
else
System.out.println("Koneksi Gagal........ !");
}
 // program mengisikan kombobox
public void IsiKombo(JComboBox kombo, String tabel, String isi, String urut ){
koneksi();
String sql="SELECT "+isi+" as hasil FROM "+tabel+" ORDER BY "+urut;
kombo.removeAllItems();
try
{
st = conn.createStatement();
rs = st.executeQuery(sql);
}
catch (SQLException e){
return;
}
try{
while (rs.next())
{
kombo.addItem(rs.getString("hasil").toString());
}
rs.close();
st.close();
}
catch (SQLException e){
return;
}
}
// Program mencari data dengan kunci
public String CariData(String tabel, String fHasil, String fKunci, String fCari ){
String hs="";
String sql="SELECT "+fHasil+" as hasil FROM "+tabel+" WHERE "+fKunci+"='"+fCari+"'";
koneksi();
try
{
st = conn.createStatement();
rs = st.executeQuery(sql);
}
catch (SQLException e){
return("");
}
try{
while (rs.next())
{
hs = rs.getString("hasil").toString();
}
rs.close();
st.close();
}
catch (SQLException e){
return("");
}
return(hs);
}
// Program menampilkan isikombo
public void CariIsiKombo(JComboBox k,String c){
int i=0;
int ketemu=0;
while (i<=k.getItemCount()-1 )
{
if (c.equals(k.getItemAt(i).toString()))
{
ketemu=i;
}
i++;
}
k.setSelectedIndex(ketemu);
}
}
 Rancangan Form untuk input data

Buatlah seperti rancangan berikut :

<!-- @page { margin: 0.79in } P { margin-bottom: 0.08in } A:link { so-language: zxx } -->

Kode Program :

package jdbc1a;
import java.sql.*;
/****************************************
*
* @author badiyanto
* STMIK AKAKOM Yogyakarta
*******************************************/
public class NewJFrame1 extends javax.swing.JFrame {
KoneksiDb x; //deklarasi kelas
/** Creates new form NewJFrame1 */
public NewJFrame1() {
initComponents();
x = new KoneksiDb();
x.koneksi(); //panggil koneksi
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*
*/
public void konek(String server,String db, String user,String passwd){
System.out.println("Keterangan");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Driver JDBC tidak barhasil Load");
e.printStackTrace();
return;
}
System.out.println("Driver berhasil di Load");
x.conn = null;
try {
x.conn = DriverManager.getConnection(
"jdbc:mysql://"+server+":3306/"+db,user,passwd);
} catch (SQLException e) {
System.out.println("Tidak bisa koneksi ke database");
e.printStackTrace();
return;
}
if (x.conn != null)
System.out.println("Berhasil Koneksi!");
else
System.out.println("Koneksi Gagal........ !");
}
private void jButtonSimpanMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String nip,nama,alamat,jk,agama,sql;
nip = jTextFieldNip.getText();
nama =jTextFieldNama.getText();
alamat=jTextFieldAlamat.getText();
if (nip.equals("") )
{
System.out.println("Nip tidak boleh kosong");
jTextFieldNip.requestFocus();
return;
}
if (nama.equals(""))
{
System.out.println("Nama tidak boleh kosong");
jTextFieldNama.requestFocus();
return;
}
if (jRadioButton1.isSelected()==true)
jk ="L";
else
jk="P";
agama=jComboBoxAgama.getItemAt(
jComboBoxAgama.getSelectedIndex()).toString();
sql="INSERT INTO pegawai(nip,nama,alamat,seks,agama) VALUES "+
"('"+nip+"','"+nama+"','"+alamat+"','"+jk+"','"+agama+"')";
jTextField1.setText(sql);
try
{
x.st = x.conn.createStatement();
x.st.execute(sql);
}
catch (SQLException e){
System.out.println("Penyimpanan Gagal ");
return;
}
System.out.println("Data sudah tersimpan!");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButtonSimpan;
private javax.swing.JComboBox jComboBoxAgama;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextFieldAlamat;
private javax.swing.JTextField jTextFieldNama;
private javax.swing.JTextField jTextFieldNip;
// End of variables declaration
}

Mengubah Rekaman

Buatlah rancangan berikut :

Kode Program :

/*
* NewJFrame2.java
*
* Created on May 22, 2011, 9:27:12 PM
*/
package jdbc1a;
import java.sql.*;
/***************************************
*
* @author badiyanto
* STMIK AKAKOM Yogyakarta
*******************************/
public class NewJFrame2 extends javax.swing.JFrame {
KoneksiDb x;
/** Creates new form NewJFrame2 */
public NewJFrame2() {
initComponents();
x = new KoneksiDb();
x.koneksi();
}
private void jButtonSimpanMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String nip,nama,alamat,jk,agama,sql;
nip = jComboBoxNip.getItemAt(jComboBoxNip.getSelectedIndex()).toString();
nama =jTextFieldNama.getText();
alamat =jTextFieldAlamat.getText();
agama =jComboBoxAgama.getItemAt(jComboBoxAgama.getSelectedIndex()).toString();
if (jRadioButton1.isSelected()==true)
jk="L";
else
jk="P";
sql = "UPDATE pegawai SET nama='"+nama+"',"+
"alamat='"+alamat+"',"+
"seks='"+jk+"',"+
"agama='"+agama+"'"+
" WHERE nip='"+nip+"'";
jTextField1.setText(sql);
try {
x.st = x.conn.createStatement();
x.st.execute(sql);
} catch (SQLException e){
System.out.println("Penyimpanan Gagal ");
return;
}
 System.out.println("data sudah tersimpan!");
 }
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
// Memgisi kombo dengan tidak memanggil fungsi di kelas KonekDB
String sql="SELECT nip FROM pegawai ORDER BY nip";
jTextField1.setText(sql);
jComboBoxNip.removeAllItems();
try
{
x.st = x.conn.createStatement();
x.rs = x.st.executeQuery(sql);
}
catch (SQLException e){
return;
}
try{
while (x.rs.next())
{
jComboBoxNip.addItem(x.rs.getString("nip").toString());
}
x.rs.close();
x.st.close();
}
catch (SQLException e){
return;
}
}
private void jComboBoxNipMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
// Menampilkan data ketika comboNip di Klik
String nip=jComboBoxNip.getItemAt(jComboBoxNip.getSelectedIndex()).toString();
String sql="SELECT * FROM pegawai WHERE nip='"+nip+"';";
try
{
x.st = x.conn.createStatement();
x.rs = x.st.executeQuery(sql);
}
catch (SQLException e){
return;
}
try{
while (x.rs.next())
{
jTextFieldNama.setText(x.rs.getString("nama").toString());
jTextFieldAlamat.setText(x.rs.getString("alamat").toString());
if (x.rs.getString("seks").equals("L"))
jRadioButton1.setSelected(true);
else
jRadioButton2.setSelected(true);
int i=0;
int ketemu=0;
while (i<=jComboBoxAgama.getItemCount()-1 )
{
if (x.rs.getString("agama").equals(
jComboBoxAgama.getItemAt(i).toString()))
{
ketemu=i;
}
i++;
}
jComboBoxAgama.setSelectedIndex(ketemu);
}
x.rs.close();
x.st.close();
}
catch (SQLException e){
return;
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame2().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButtonSimpan;
private javax.swing.JComboBox jComboBoxAgama;
private javax.swing.JComboBox jComboBoxNip;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextFieldAlamat;
private javax.swing.JTextField jTextFieldNama;
// End of variables declaration
}
Menghapus Rekaman
Rancangan Form Berikut :
Kode Program

<!-- @page { margin: 0.79in } P { margin-bottom: 0.08in } -->
/***********************************************
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/************************************************
/***********************************************
* NewJFrame3.java
*
* Created on May 30, 2011, 9:28:42 PM
***********************************************/
package jdbc1a;
import java.sql.*;
import javax.swing.JOptionPane;
/*********************************************
*
* @author badiyanto
* STMIK AKAKOM Yogyakarta
*********************************************/
public class NewJFrame3 extends javax.swing.JFrame {
KoneksiDb y;
/** Creates new form NewJFrame3 */
public NewJFrame3() {
initComponents();
y=new KoneksiDb();
y.koneksi();
}
/** This method is called from within the constructor to
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
// memanggil fungsi kosongkan isian
kosongkan();
}
private void jComboBoxNipMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String nip=jComboBoxNip.getItemAt(jComboBoxNip.getSelectedIndex()).toString();
///menampilkan isian dengan memanggil fungsi y.Caridata(......);
jTextFieldNama.setText(y.CariData("pegawai","nama","nip", nip));
jTextFieldAlamat.setText(y.CariData("pegawai","alamat","nip", nip));
if (y.CariData("pegawai","seks","nip", nip).equals("L"))
jRadioButton1.setSelected(true);
else
jRadioButton2.setSelected(true);
y.CariIsiKombo(jComboBoxAgama,y.CariData("pegawai","agama","nip", nip).toString());
}
//proses menghapus rekaman//
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String nip=jComboBoxNip.getItemAt(jComboBoxNip.getSelectedIndex()).toString();
// dialog konfirmasi //
int jawab=JOptionPane.showConfirmDialog(this,"Anda yakin ingim menghapus data ini","Konfimasi",JOptionPane.YES_NO_OPTION);
if (jawab == 0)
{
try
{
y.st = y.conn.createStatement();
y.st.execute("DELETE FROM pegawai WHERE nip='"+nip+"'");
}
catch (SQLException e){
System.out.println("Gagal mengapus Gagal ");
return;
}
System.out.println("Data Berhasil dihapus!");
kosongkan();
}
}
void kosongkan()
{
jTextFieldAlamat.setText("");
jTextFieldNama.setText("");
jRadioButton1.setSelected(false);
jRadioButton2.setSelected(false);
jComboBoxAgama.setSelectedIndex(0);
jComboBoxNip.requestFocus();
y.IsiKombo(jComboBoxNip,"pegawai","nip", "nip");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame3().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JComboBox jComboBoxAgama;
private javax.swing.JComboBox jComboBoxNip;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JTextField jTextFieldAlamat;
private javax.swing.JTextField jTextFieldNama;
// End of variables declaration
}

Entry filed under: Uncategorized. Tags: .

Virus Flu Burung Membuat Windows XP Tidak Bisa Login

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Waktu

Calender

August 2011
M T W T F S S
« Jun    
1234567
891011121314
15161718192021
22232425262728
293031  

Recent Posts

Archieves

Pengunjung

Deni Nurmawan

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 4 other followers

Recent Comments

heru on
heru on
Luckman R on
aziz on

%d bloggers like this: