Wednesday, June 20, 2012

Membuat Kode Otomatis Sederhana

 Disini saya akan buat kode otomatis sesuai dengan table sql, yang ingin ditampilkan misalkan KB001, KB002, ....., dan seterusnya.

Pertama buat tabel misalkan kita sudah buat database (db_penjualan) dan tinggal membuat databasenya.
Syntak:
CREATE TABLE tb_barang (
kd_brg varchar(5) PRIMARY KEY,
nama_brg varchar(30),
jenis_brg varchar(30)
)

***************
String koneksi="jdbc:mysql://localhost/db_penjualan";
String user="root";
String pass="";
Statement statement;
Connection connection;
private void nourut(){
try{
String sql="select right(kd_brg,2) as no_terakhir from tb_barang";
ResultSet rs=statement.executeQuery(sql);
if (rs.first()==false)
{
txtno_urut.setText("KB001");
}
else
{
rs.last();
int no=rs.getInt(1)+1;
String cno=String.valueOf(no);
int pjg_cno=cno.length();
for (int i = 0; i < 2-pjg_cno; i++)
{
cno="00"+cno;
}
txtno_urut.setText("KB"+ cno);
}
}
catch (Exception DBException)
{
System.err.println("Error ="+ DBException);
}
}

****copy syntax diatas tepat dibawah syntak
public Barang() {
initComponents();
}
*****

kemudian copy syntak dibawah ini pada formWindowOpened
(klik kanan form>event>window>windowOpened)

try
{
Class.forName("com.mysql.jdbc.Driver");
koneksi="jdbc:mysql://localhost/db_penjualan";
connection=DriverManager.getConnection(koneksi,user,pass);
statement=connection.createStatement();
nourut();
}
catch (Exception DBException)
{
JOptionPane.showMessageDialog(this, "koneksi gagal",
"error", JOptionPane.ERROR_MESSAGE);
System.err.println("Error ="+DBException);
}

Silahkan dikembangkan sendiri...^^

No comments:

Post a Comment

Followers