Java-SQL : Input Data Sederhana

//Source Lengkapnya:
//4.a
import javax.swing.*;
import java.sql.*;
import java.text.*;
import javax.swing.table.*;
import java.util.*;
public class frmDosen extends javax.swing.JFrame {
//4.b
public frmDosen() {
initComponents();
testDriver();
kosongkan();
tKode.setText(“”);
updateTabel();
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
tKode = new javax.swing.JTextField();
tNama = new javax.swing.JTextField();
tAlamat = new javax.swing.JTextField();
tTglLahir = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
tabel = new javax.swing.JTable();
jPanel2 = new javax.swing.JPanel();
bSimpan = new javax.swing.JButton();
bHapus = new javax.swing.JButton();
bBatal = new javax.swing.JButton();

setTitle(“Form Dosen”);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});

jPanel1.setLayout(null);

jPanel1.setBackground(new java.awt.Color(0, 204, 204));
jLabel1.setFont(new java.awt.Font(“Arial”, 1, 12));
jLabel1.setText(“Kode”);
jPanel1.add(jLabel1);
jLabel1.setBounds(50, 50, 60, 30);

jLabel2.setFont(new java.awt.Font(“Arial”, 1, 12));
jLabel2.setText(“Nama”);
jPanel1.add(jLabel2);
jLabel2.setBounds(50, 90, 60, 30);

jLabel3.setFont(new java.awt.Font(“Arial”, 1, 12));
jLabel3.setText(“Alamat”);
jPanel1.add(jLabel3);
jLabel3.setBounds(50, 130, 60, 30);

jLabel4.setFont(new java.awt.Font(“Arial”, 1, 12));
jLabel4.setText(“Tgl Lahir”);
jPanel1.add(jLabel4);
jLabel4.setBounds(50, 170, 60, 30);

tKode.setBackground(new java.awt.Color(204, 255, 204));
tKode.setFont(new java.awt.Font(“Tahoma”, 1, 12));
tKode.setText(“tKode”);
tKode.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
tKode.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tKodeActionPerformed(evt);
}
});
tKode.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
tKodeFocusGained(evt);
}
});

jPanel1.add(tKode);
tKode.setBounds(120, 50, 110, 30);

tNama.setBackground(new java.awt.Color(204, 255, 204));
tNama.setFont(new java.awt.Font(“Tahoma”, 1, 12));
tNama.setText(“tNama”);
tNama.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
tNama.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tNamaActionPerformed(evt);
}
});
tNama.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
tNamaFocusGained(evt);
}
});

jPanel1.add(tNama);
tNama.setBounds(120, 90, 240, 30);

tAlamat.setBackground(new java.awt.Color(204, 255, 204));
tAlamat.setFont(new java.awt.Font(“Tahoma”, 1, 12));
tAlamat.setText(“tAlamat”);
tAlamat.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
tAlamat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tAlamatActionPerformed(evt);
}
});
tAlamat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
tAlamatFocusGained(evt);
}
});

jPanel1.add(tAlamat);
tAlamat.setBounds(120, 130, 240, 30);

tTglLahir.setBackground(new java.awt.Color(204, 255, 204));
tTglLahir.setFont(new java.awt.Font(“Tahoma”, 1, 12));
tTglLahir.setText(“tTglLahir”);
tTglLahir.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
tTglLahir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tTglLahirActionPerformed(evt);
}
});
tTglLahir.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
tTglLahirFocusGained(evt);
}
});

jPanel1.add(tTglLahir);
tTglLahir.setBounds(120, 170, 240, 30);

tabel.setBorder(new javax.swing.border.EtchedBorder());
tabel.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
“Title 1”, “Title 2”, “Title 3”, “Title 4”
}
));
tabel.setGridColor(new java.awt.Color(204, 204, 255));
tabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tabelMouseClicked(evt);
}
});

jScrollPane1.setViewportView(tabel);

jPanel1.add(jScrollPane1);
jScrollPane1.setBounds(4, 214, 460, 110);

getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

jPanel2.setLayout(new java.awt.GridLayout(1, 0));

bSimpan.setBackground(new java.awt.Color(0, 153, 153));
bSimpan.setText(“Simpan”);
bSimpan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bSimpanActionPerformed(evt);
}
});
bSimpan.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
bSimpanKeyPressed(evt);
}
});

jPanel2.add(bSimpan);

bHapus.setBackground(new java.awt.Color(0, 153, 153));
bHapus.setText(“Hapus”);
bHapus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bHapusActionPerformed(evt);
}
});

jPanel2.add(bHapus);

bBatal.setBackground(new java.awt.Color(0, 153, 153));
bBatal.setText(“Batal”);
bBatal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bBatalActionPerformed(evt);
}
});

jPanel2.add(bBatal);

getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-473)/2, (screenSize.height-381)/2, 473, 381);
}
//5.c
private void tabelMouseClicked(java.awt.event.MouseEvent evt) {
tKode.setText(tabel.getValueAt(tabel.getSelectedRow(), 0).toString().trim());
tKodeActionPerformed(null);
}
//4.e
private void bHapusActionPerformed(java.awt.event.ActionEvent evt) {
try{
sql=”delete from dosen where kode_dsn='”+tKode.getText().trim()+”‘ “;
stmt.executeUpdate(sql);
System.out.println(sql);
}catch(SQLException e){JOptionPane.showMessageDialog(this,”Gagal, “+e);}
updateTabel();
kosongkan();
}
//5.a
private void bSimpanKeyPressed(java.awt.event.KeyEvent evt) {
bSimpanActionPerformed(null);
}
//5.d
private void tTglLahirFocusGained(java.awt.event.FocusEvent evt) {
tTglLahir.selectAll();
}
//5.d
private void tAlamatFocusGained(java.awt.event.FocusEvent evt) {
tAlamat.selectAll();
}
//5.d
private void tNamaFocusGained(java.awt.event.FocusEvent evt) {
tKode.selectAll();
}
//5.d
private void tKodeFocusGained(java.awt.event.FocusEvent evt) {
tKode.selectAll();
}
//4.e
private void bBatalActionPerformed(java.awt.event.ActionEvent evt) {
kosongkan();
}
//4.e
private void bSimpanActionPerformed(java.awt.event.ActionEvent evt) {
try{
sql=”select count(*) from dosen where kode_dsn='”+tKode.getText().trim()+”‘”;
hasil=stmt.executeQuery(sql);
hasil.next();
if(Integer.parseInt(hasil.getString(1))<1){
sql=”insert into dosen values (‘”+tKode.getText()+”‘,'”+tNama.getText()+”‘,'”+tAlamat.getText()+”‘,'”+setTanggal(tTglLahir.getText())+”‘) “;
stmt.executeUpdate(sql);
System.out.println(sql);
}else{
sql=”update dosen set Nama='”+tNama.getText()+”‘, Alamat='”+tAlamat.getText()+”‘, Tgl_Lahir='”+tTglLahir.getText()+”‘ where kode_dsn='”+tKode.getText().trim()+”‘ “;
stmt.executeUpdate(sql);
System.out.println(sql);
}
}catch(SQLException e){JOptionPane.showMessageDialog(this,”Gagal, “+e);}
kosongkan();
updateTabel();
tKode.requestFocus();
}
//5.e
private void tTglLahirActionPerformed(java.awt.event.ActionEvent evt) {
bSimpan.requestFocus();
}
//5.e
private void tAlamatActionPerformed(java.awt.event.ActionEvent evt) {
tTglLahir.requestFocus();
}
//5.e
private void tNamaActionPerformed(java.awt.event.ActionEvent evt) {
tAlamat.requestFocus();
}
//5.b
private void tKodeActionPerformed(java.awt.event.ActionEvent evt) {
try{
sql=”select count(*) from dosen where kode_dsn='”+tKode.getText().trim()+”‘”;
hasil=stmt.executeQuery(sql);
hasil.next();
if(Integer.parseInt(hasil.getObject(1).toString())>=1){
sql=”select Nama,Alamat,tgl_lahir from dosen where kode_dsn='”+tKode.getText().trim()+”‘”;
hasil=stmt.executeQuery(sql);
hasil.next();
tNama.setText(hasil.getString(1));
tAlamat.setText(hasil.getString(2));
tTglLahir.setText(getTanggal(hasil.getDate(3)));
bHapus.setEnabled(true);
}else{
kosongkan();
}
tNama.requestFocus();
}catch(SQLException e){JOptionPane.showMessageDialog(this,”Gagal, “+e);}
}

/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
new frmDosen().show();
}
//4.d
private void kosongkan(){
tNama.setText(“”);
tAlamat.setText(“”);
tTglLahir.setText(“”);
bHapus.setEnabled(false);
}
//4.d
public void testDriver(){
try{
Class.forName(dbDrv);
con = DriverManager.getConnection(dbUrl,sqlUser,sqlPass);
stmt=con.createStatement();
}catch(Exception ce){
System.out.println(ce.toString());
}
}
//4.d
private void updateTabel(){
tabel.setModel(model=new DefaultTableModel());
//tabel.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
try{
sql=”SELECT * FROM dosen”;
ResultSet hasil=stmt.executeQuery(sql);
ResultSetMetaData rsKolom=hasil.getMetaData();
for(int I=1;I<=rsKolom.getColumnCount();I++)
model.addColumn(rsKolom.getColumnName(I).trim());
Vector V=null;
for(int I=0;hasil.next();I++){
V=new Vector();
for(int J=1;J<=hasil.getMetaData().getColumnCount();J++){
V.add(hasil.getObject(J));
}
model.addRow(V);
}
}catch(Exception e){System.err.println(e.getMessage()+”2″);}
}
//4.d
public String getTanggal(java.util.Date d){
return new SimpleDateFormat(“dd/MM/yyyy”).format(d);
}
//4.d
public String setTanggal(String d){
try{
return new SimpleDateFormat(“MM/dd/yyyy”).format(new SimpleDateFormat(“dd/MM/yyyy”).parse(d));
}catch(Exception e){return null;}
}
// Variables declaration – do not modify//GEN-BEGIN:variables
private javax.swing.JButton bBatal;
private javax.swing.JButton bHapus;
private javax.swing.JButton bSimpan;
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.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField tAlamat;
private javax.swing.JTextField tKode;
private javax.swing.JTextField tNama;
private javax.swing.JTextField tTglLahir;
private javax.swing.JTable tabel;
// End of variables declaration//GEN-END:variables

//4.c
private String sql,sql2;
private Connection con;
private Statement stmt;
private ResultSet hasil,hasil2;
private String sqlUser=”sa”; //UserName untuk administrator SQL server
private String sqlPass=”sa”; //Password untuk administrator SQL server
private String sqlDb=”dbKuliah”; //Database yang diakses
private String koneksiOdbc=”koneksi”; //Nama koneksi odbc
//2 Pilih tergantung jenis koneksi
private String dbDrv = “sun.jdbc.odbc.JdbcOdbcDriver”;
//private String dbDrv = “com.microsoft.jdbc.sqlserver.SQLServerDriver”;
private String dbUrl = “jdbc:odbc:”+koneksiOdbc;
//private String dbUrl = “jdbc:microsoft:sqlserver://localhost;DatabaseName=”+sqlDb;
private DefaultTableModel model;
}
Selengkapnya…

Menampilkan Tanggal dan Jam pada NetBeans

OutPut:

Coding:

Penjelasan:
Jadi untuk waktu %1$tH adalah angka Jam jumlah 2 digit
%1$tM adalah angka Menit jumlah 2 digit
%1$tS adalah angka Detik jumlah 2 digit
Untuk Tanggal %1$td adalah hari bentuk angka 2 digit
%1$tm adalah bulan bentuk bulan sesuai seting di regional setting
anda di control panel
%1$tY adalah tahun bentuk angka 4 digit Jadi semua ini yang memenentukan sesuai dengan seting computer kita di Regional Setting.

Berikut Penjelasan untuk lebih lanjut:
H adalah jam dengan format 2 digit angka 00-23
I adalah jam dengan format 2 digit angka 01-12
M adalah menit dalam 1 jam format 00-59
S adalah detik dalam 1 menit format 00-60
B adalah nama bulan dalam karakter
m adalah nama bulan dengan format angka 2 digit
d adalah hari dalam 1 bulan 01-31
Y adalah tahun dalam format 4 angka
F adalah format tanggal otomatis yang sudah langsung jadi yaitu “%1$tY-1$%tm-1$%td”
jadinya 2008-12-01,tahun,bulan,tanggal.
T adalah format jam yang otomatis yang sudah jadi yaitu “1$%tH:1$%tM:1$%tS”
12:10:38,jam,menit,detik.

http://ibasbloger.blogspot.com/2008/10/menampilkan-tanggal-dan-jam-di-java.html

Tampilkan database MySQL ke JTable Java dengan NetBean 5.0

Code:

import java.awt.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.*;

public class SimpleTable extends JPanel {

private String user = "root";
private String pass = "";
private String url = "jdbc:mysql://localhost/penjualan";
private String[] header = {"Item Code","Description","Item Group"};

private Connection conn;
private Statement stmt;
private ResultSet rs;

private JTable table;
JScrollPane scrollTable;
private Object[][] dataTable = null;

public SimpleTable() {
super(new BorderLayout());

table = new JTable();
scrollTable = new JScrollPane();
scrollTable.setViewportView(table);

try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.err.println("Class Driver tidak ditemukan : " + cnfe.getMessage());
}

try {
conn = DriverManager.getConnection(url, user, pass);
stmt = conn.createStatement();

String query = "SELECT * FROM tbarang";
rs = stmt.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
int col = meta.getColumnCount();
int baris = 0;
while(rs.next()) {
baris = rs.getRow();
}

dataTable = new Object[baris][col];
int x = 0;
rs.beforeFirst();
while(rs.next()) {
dataTable[x][0] = rs.getString("itemcode");
dataTable[x][1] = rs.getString("description");
dataTable[x][2] = rs.getString("itemgroup");
x++;
}
table.setModel(new DefaultTableModel(dataTable, header));

add(scrollTable, BorderLayout.NORTH);

stmt.close();
rs.close();
conn.close();

} catch (SQLException se) {
System.err.println("Kesalahan perintah SQL : " + se.getMessage());
}
}

private static void tampilkanGUI() {
JFrame frame = new JFrame("Contoh Data dari Database");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

SimpleTable content = new SimpleTable();
content.setOpaque(true);
frame.setContentPane(content);

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
tampilkanGUI();
}
});
}

http://www.goldenstudios.or.id/forum/showthread.php?tid=1734

Mengisi data dari JTable ke JTextField

di dalam JTable itu ada method2 berikut ini yg bisa dipakai sesuai dgn kasusnya:

Code:
int     getSelectedColumn()
Returns the index of the first selected column, -1 if no column is selected.

int     getSelectedRow()
Returns the index of the first selected row, -1 if no row is selected.

Object     getValueAt(int row, int column)
Returns the cell value at row and column.

jadi kesimpulan tuk ambil sebuah data dalam kolom dan row tertentu bisa spt ini:
Code:
String data = jTable.getValueAt(jTable.getSelectedRow(), jTable.getSelectedColumn());
atau:
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
try {
String datax =String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), jTable1.getSelectedColumn()));
jTextField1.setText(datax);
}
catch (Exception e){}
}

Mengakses Database Ms Access dengan Java

package org.mojo.blog.Java_depth.aboutMsOffice;

import Java.sql.*;

/**
* Created by IntelliJ IDEA.<br>
* User: Mojo<br>
* Date: 08 Feb 09<br>
* Time: 22:30:08<p>
*/
public class MsAccessJava {
private static String driverName = “sun.jdbc.odbc.JdbcOdbcDriver”;
private static String url = “jdbc:odbc:JavaMsAccess”;
public static void main(String[] args) {
String sql =”SELECT * from tblCustomer”;
try {
Class.forName(driverName);
Connection conn = DriverManager.getConnection(url);
System.out.println(“Connection Established..”);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()){
System.out.println(“+————- Detail Customer ———————-+”);
System.out.println(“Customer ID : “+ rs.getInt(1));
System.out.println(“Customer Name : “+ rs.getString(2));
System.out.println(“Customer Address : “+ rs.getString(3));
System.out.println(“Customer Phone : “+ rs.getString(4));
System.out.println(“+—————————————————-+”);
System.out.println(“\n”);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

http://josescalia.blogspot.com/2009/02/mengakses-database-ms-access-dengan.html