suhe arie's pages

Programmer juga manusia

Pengolahan database dengan Java ? No problem

Aplikasi dan database adalah dua hal yang sangat berkaitan. Hampir mustahil rasanya jika kita membuat sebuah aplikasi yang cukup besar, tanpa adanya database. Sebaliknya, dengan database yang besar, tapi tidak ada aplikasi, user akan mengalami kesulitan saat akan melakukan pengolahan data. Untuk ini semua, kita membutuhkan bahasa pemrograman yang menyediakan fasilitas untuk melakukan pengolahan database dengan mudah.

Java menyediakan fitur pengolahan database ini dengan cukup baik melalui teknologi yang dinamakan Java Database Connectivity (JDBC). JDBC ini sebenarnya adalah sebuah spesifikasi yang mengatur bagaimana sebuah database server dapat diolah dari aplikasi Java. Implementasi dari JDBC ini dibuat oleh masing-masing vendor database berupa sebuah library yang berisi kumpulan class yang mengikuti standar/spesifikasi JDBC, biasanya disebut juga sebagai JDBC driver. Oleh karena itu, masing-masing database mempunyai driver JDBC sendiri seperti Oracle menamainya SQLJ/JDBC, MySQL menamainya MySQL Connector/J.

Lho ? Jadi cara akses databasenya beda-beda, sesuai dengan database yang digunakan ?
Untungnya tidak demikian, jangan khawatir. Idealnya, kita bisa menggunakan konsep yang sama, cara pengolahan yang sama, source code yang sama, class yang sama untuk mengolah berbagai macam database yang sudah memiliki implementasi JDBC driver. Jadi jika kita ingin menghubungkan aplikasi Java kita dengan database lain, kita cukup mengubah JDBC driver dan connection propertiesnya saja.

Pada contoh kali ini kita akan melakukan pengolahan data sederhana menggunakan database MySQL. Untuk ini, kita membutuhkan MySQL versi 5 dan MySQL JDBC Driver versi 5.0. Silahkan install MySQL servernya, jika belum terinstall. Ada baiknya anda menginstall MySQL GUI Tools juga untuk memudahkan administrasi database. Untuk Java nya, Anda dapat menggunakan IDE apa saja, saya menggunakan Eclipse IDE.

Asumsi saya, Anda sudah:
1. Paham tentang dasar pemrograman Java.
2. Paham tentang dasar-dasar SQL.

Setup database

Anda bisa pakai command line, MySQL GUI, atau Eclipse Data Tools untuk melakukan langkah-langkah berikut.

a. Create database

create database myblog;

b. Create table

CREATE TABLE `myblog`.`MASTER_BARANG` (
`N_ID` INTEGER UNSIGNED NOT NULL,
`S_NAMA` VARCHAR(100) NOT NULL DEFAULT '',
`N_HARGA` DECIMAL(10,2) NOT NULL DEFAULT 0,
`S_KATEGORI` VARCHAR(255) NOT NULL DEFAULT '',
`N_STOK` INTEGER UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY(`N_ID`)
)
ENGINE = InnoDB;

Hasilnya seperti ini:

Kita mulai java-nya

1. Setup project di eclipse

Ekstrak file mysql-connector-java-5.0.8-bin.jar dari dalam file zip hasil download JDBC driver dan copy ke folder lib di dalam project. Kemudian, include file jar tersebut ke dalam build path project, caranya klik kanan di file tersebut, pilih Build Path -> Add to Build Path.

2. DB Connection Manager

Kita akan membuat sebuah class sederhana, yang bertugas untuk melakukan koneksi ke database. Di method main, saya tulis cara penggunaannya sekaligus untuk mengetes koneksinya.

Langkah-langkah untuk membuat koneksi ke database:
a. Load class JDBC drivernya.
b. Register ke DriverManager
c. Get connection, dengan menyertakan username, password dan connection URL.

Cara paling sederhana untuk melakukan query adalah menggunakan object Statement.
a. Create object Statement dari connection.
b. Panggil method executeQuery untuk melakukan pembacaan data (query SELECT).
c. Panggil method executeUpdate untuk melakukan perubahan data (INSERT, UPDATE, DELETE, dsb).

package suhearie.blog.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBManager {

	// nama class driver yang digunakan
	private String dbDriver = "com.mysql.jdbc.Driver";

	// connection url, format [protokol]://[hostname]/[databasename]
	private String dbUrl = "jdbc:mysql://localhost/myblog";

	// username
	private String dbUser = "hendra";

	// password
	private String dbPswd = "hendra";

	public DBManager() {
		try {
			// load class driver
			Driver driver = (Driver) Class.forName(dbDriver).newInstance();

			// register ke driver manager
			DriverManager.registerDriver(driver);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Connection getConnection() {
		// connect ke database
		try {
			return DriverManager.getConnection(dbUrl, dbUser, dbPswd);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public ResultSet executeQuery(String sql) {
		Connection conn = getConnection();
		try {
			Statement stmt = conn.createStatement();
			return stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public int executeUpdate(String sql) {
		Connection conn = getConnection();
		try {
			Statement stmt = conn.createStatement();
			return stmt.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}
	}

	public static void main(String[] args) {
		DBManager manager = new DBManager();
		Connection conn = manager.getConnection();

		try {
			// Print beberapa informasi tentang server
			System.out.println(conn.getMetaData().getDatabaseProductName());
			System.out.println(conn.getMetaData().getDatabaseProductVersion());
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}

3. Entity class

Di Java, kita dapat melakukan operasi database secara langsung dengan memberikan parameter-parameter berupa nilai dari tiap kolom yang ada di tabel. Tapi, itu bukan cara yang baik. Kita membutuhkan class (biasanya disebut bean class atau entity) yang merupakan representasi dari data yang tersimpan dalam tabel. Umumnya, satu instance dari class ini mewakili satu row di database.

Keuntungan menggunakan entity ini, data lebih mudah diolah dan code akan lebih mudah dibaca. Skenarionya adalah, kita membaca data dari tabel, mengubahnya menjadi sebuah object di memory, memanipulasi object tersebut, kemudian menyimpannya kembali ke database. Jadi data yang ada di tabel, tidak berserakan kemana-mana, karena kita mempunyai object “pembungkusnya”. Metode ini akan sangat berguna sebagai dasar jika kita melangkah ke teknologi Java yang lebih canggih, yaitu persistence engine.

package suhearie.blog.jdbc;

public class BarangBean {

	private int id = 0;

	private String nama = "";

	private double harga = 0;

	private String kategori = "";

	private int stok = 0;

	public BarangBean() {}

	public BarangBean(int id, String nama, double harga, String kategori,
			int stok) {
		super();
		this.id = id;
		this.nama = nama;
		this.harga = harga;
		this.kategori = kategori;
		this.stok = stok;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getNama() {
		return nama;
	}

	public void setNama(String nama) {
		this.nama = nama;
	}

	public double getHarga() {
		return harga;
	}

	public void setHarga(double harga) {
		this.harga = harga;
	}

	public String getKategori() {
		return kategori;
	}

	public void setKategori(String kategori) {
		this.kategori = kategori;
	}

	public int getStok() {
		return stok;
	}

	public void setStok(int stok) {
		this.stok = stok;
	}

}

Tidak ada yang istimewa dari class ini. Hanya merupakan kumpulan property yang sinkron dengan kolom di tabel, dan selebihnya merupakan getter (accessor) dan setter (mutator) method.

4. GUI tabel

Kita menggunakan JFrame untuk menampilkan data dalam bentuk tabel. Selain itu kita mempunyai toolbar yang berisi tombol-tombol untuk add, edit, dan delete.

package suhearie.blog.jdbc;

import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.JToolBar;
import java.awt.GridBagConstraints;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.table.DefaultTableModel;

public class MainFrame extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JToolBar jJToolBarBar = null;
	private JScrollPane jScrollPane = null;
	private JTable table = null;
	private JButton btnAdd = null;
	private JButton btnEdit = null;
	private JButton btnDelete = null;
	private DBManager manager = null;  //  @jve:decl-index=0:visual-constraint="537,53"

	/**
	 * This method initializes jJToolBarBar
	 *
	 * @return javax.swing.JToolBar
	 */
	private JToolBar getJJToolBarBar() {
		if (jJToolBarBar == null) {
			jJToolBarBar = new JToolBar();
			jJToolBarBar.add(getBtnAdd());
			jJToolBarBar.add(getBtnEdit());
			jJToolBarBar.add(getBtnDelete());
		}
		return jJToolBarBar;
	}

	/**
	 * This method initializes jScrollPane
	 *
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getTable());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes table
	 *
	 * @return javax.swing.JTable
	 */
	private JTable getTable() {
		if (table == null) {
			DefaultTableModel model = new DefaultTableModel(null, new String[] {
					"ID", "NAMA", "HARGA", "KATEGORI", "STOK"});
			table = new JTable(model);
		}
		return table;
	}

	/**
	 * This method initializes btnAdd
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBtnAdd() {
		if (btnAdd == null) {
			btnAdd = new JButton();
			btnAdd.setText("Add");
			btnAdd.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					add();
				}
			});
		}
		return btnAdd;
	}

	private void add() {
		new EditorDialog(this, null).setVisible(true);
	}

	/**
	 * This method initializes btnEdit
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBtnEdit() {
		if (btnEdit == null) {
			btnEdit = new JButton();
			btnEdit.setText("Edit");
			btnEdit.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					edit();
				}
			});
		}
		return btnEdit;
	}

	private void edit() {
		Integer id = (Integer) table.getValueAt(table.getSelectedRow(), 0);
		String sql = "SELECT * FROM MASTER_BARANG WHERE N_ID = "+id;
		ResultSet rs = getManager().executeQuery(sql);
		try {
			if (rs.next()) {
				BarangBean bean = new BarangBean(rs.getInt("N_ID"),
						rs.getString("S_NAMA"),
						rs.getDouble("N_HARGA"),
						rs.getString("S_KATEGORI"),
						rs.getInt("N_STOK"));
				new EditorDialog(this, bean).setVisible(true);
			}
			else {
				refresh();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * This method initializes btnDelete
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBtnDelete() {
		if (btnDelete == null) {
			btnDelete = new JButton();
			btnDelete.setText("Delete");
			btnDelete.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					delete();
				}
			});
		}
		return btnDelete;
	}

	private void delete() {
		int[] rows = table.getSelectedRows();
		String sql = "DELETE FROM MASTER_BARANG WHERE N_ID IN (";
		for (int row : rows) {
			sql += table.getValueAt(row, 0)+",";
		}
		// remove last comma
		sql = sql.substring(0, sql.length()-1);
		sql += ")";
		manager.executeUpdate(sql);
		refresh();
	}

	/**
	 * This method initializes manager1
	 *
	 * @return suhearie.blog.jdbc.DBManager
	 */
	public DBManager getManager() {
		if (manager == null) {
			manager = new DBManager();
		}
		return manager;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				MainFrame thisClass = new MainFrame();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		});
	}

	/**
	 * This is the default constructor
	 */
	public MainFrame() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 *
	 * @return void
	 */
	private void initialize() {
		this.setSize(415, 297);
		this.setContentPane(getJContentPane());
		this.setTitle("Main Frame");
		refresh();
	}

	public void refresh() {
		String sql = "SELECT * FROM MASTER_BARANG ORDER BY N_ID";
		ResultSet rs = getManager().executeQuery(sql);
		if (rs != null) {
			DefaultTableModel model = (DefaultTableModel) table.getModel();
			for (int i=table.getRowCount()-1; i>=0; i--) {
				model.removeRow(i);
			}
			try {
				while (rs.next()) {
					Object[] data = new Object[] {
							rs.getInt("N_ID"),
							rs.getString("S_NAMA"),
							rs.getDouble("N_HARGA"),
							rs.getString("S_KATEGORI"),
							rs.getInt("N_STOK")
							};
					model.addRow(data);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * This method initializes jContentPane
	 *
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.fill = GridBagConstraints.BOTH;
			gridBagConstraints1.gridy = 1;
			gridBagConstraints1.weightx = 1.0;
			gridBagConstraints1.weighty = 1.0;
			gridBagConstraints1.gridx = 0;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.fill = GridBagConstraints.BOTH;
			gridBagConstraints.gridy = 0;
			gridBagConstraints.weightx = 1.0;
			gridBagConstraints.gridx = 0;
			jContentPane = new JPanel();
			jContentPane.setLayout(new GridBagLayout());
			jContentPane.add(getJJToolBarBar(), gridBagConstraints);
			jContentPane.add(getJScrollPane(), gridBagConstraints1);
		}
		return jContentPane;
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"

Tombol Add ditekan, tampilkan EditorDialog kosong, sehingga user bisa memasukkan data baru.

Tombol Edit ditekan, tampilkan EditorDialog yang berisi data yang ingin diedit.

Tombol Delete ditekan, hapus data yang dipilih.

5. GUI data editor

Kita menggunakan JDialog untuk menampilkan form untuk menambah data baru dan mengedit data.

package suhearie.blog.jdbc;

import javax.swing.JPanel;
import java.awt.Frame;
import java.awt.BorderLayout;
import javax.swing.JDialog;
import java.awt.GridBagLayout;
import java.awt.Dimension;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import javax.swing.JTextField;
import java.awt.Insets;
import javax.swing.JButton;

public class EditorDialog extends JDialog {

	private static final long serialVersionUID = 1L;
	private boolean newBean;
	private MainFrame parent;
	private BarangBean bean;  //  @jve:decl-index=0:
	private JPanel jContentPane = null;
	private JLabel jLabel = null;
	private JLabel jLabel1 = null;
	private JLabel jLabel2 = null;
	private JLabel jLabel3 = null;
	private JLabel jLabel4 = null;
	private JTextField txtId = null;
	private JTextField txtNama = null;
	private JTextField txtHarga = null;
	private JTextField txtKategori = null;
	private JTextField txtStok = null;
	private JButton btnSave = null;
	private JButton btnCancel = null;

	/**
	 * @param owner
	 */
	public EditorDialog(Frame owner) {
		super(owner);
		initialize();
	}

	public EditorDialog(MainFrame parent, BarangBean bean) {
		super(parent, true);
		initialize();
		this.parent = parent;
		this.bean = bean;
		displayBean();
	}

	private void displayBean() {
		if (bean == null) {
			bean = new BarangBean();
			newBean = true;
		}
		else {
			newBean = false;
			txtId.setEditable(false);
		}
		txtId.setText(String.valueOf(bean.getId()));
		txtNama.setText(bean.getNama());
		txtHarga.setText(String.valueOf(bean.getHarga()));
		txtKategori.setText(bean.getKategori());
		txtStok.setText(String.valueOf(bean.getStok()));
	}

	/**
	 * This method initializes this
	 *
	 * @return void
	 */
	private void initialize() {
		this.setSize(359, 257);
		this.setTitle("Add / Edit Barang");
		this.setContentPane(getJContentPane());
	}

	/**
	 * This method initializes jContentPane
	 *
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			GridBagConstraints gridBagConstraints41 = new GridBagConstraints();
			gridBagConstraints41.gridx = 2;
			gridBagConstraints41.anchor = GridBagConstraints.WEST;
			gridBagConstraints41.insets = new Insets(15, 5, 5, 5);
			gridBagConstraints41.gridy = 5;
			GridBagConstraints gridBagConstraints31 = new GridBagConstraints();
			gridBagConstraints31.gridx = 1;
			gridBagConstraints31.anchor = GridBagConstraints.WEST;
			gridBagConstraints31.insets = new Insets(15, 5, 5, 5);
			gridBagConstraints31.gridy = 5;
			GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
			gridBagConstraints21.fill = GridBagConstraints.VERTICAL;
			gridBagConstraints21.gridy = 4;
			gridBagConstraints21.weightx = 1.0;
			gridBagConstraints21.anchor = GridBagConstraints.WEST;
			gridBagConstraints21.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints21.gridwidth = 2;
			gridBagConstraints21.gridx = 1;
			GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
			gridBagConstraints11.fill = GridBagConstraints.VERTICAL;
			gridBagConstraints11.gridy = 3;
			gridBagConstraints11.weightx = 1.0;
			gridBagConstraints11.anchor = GridBagConstraints.WEST;
			gridBagConstraints11.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints11.gridwidth = 2;
			gridBagConstraints11.gridx = 1;
			GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
			gridBagConstraints7.fill = GridBagConstraints.VERTICAL;
			gridBagConstraints7.gridy = 2;
			gridBagConstraints7.weightx = 1.0;
			gridBagConstraints7.anchor = GridBagConstraints.WEST;
			gridBagConstraints7.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints7.gridwidth = 2;
			gridBagConstraints7.gridx = 1;
			GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
			gridBagConstraints6.fill = GridBagConstraints.VERTICAL;
			gridBagConstraints6.gridy = 1;
			gridBagConstraints6.weightx = 1.0;
			gridBagConstraints6.anchor = GridBagConstraints.WEST;
			gridBagConstraints6.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints6.gridwidth = 2;
			gridBagConstraints6.gridx = 1;
			GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
			gridBagConstraints5.fill = GridBagConstraints.VERTICAL;
			gridBagConstraints5.gridy = 0;
			gridBagConstraints5.weightx = 1.0;
			gridBagConstraints5.anchor = GridBagConstraints.WEST;
			gridBagConstraints5.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints5.gridwidth = 2;
			gridBagConstraints5.gridx = 1;
			GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
			gridBagConstraints4.gridx = 0;
			gridBagConstraints4.anchor = GridBagConstraints.WEST;
			gridBagConstraints4.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints4.gridy = 4;
			jLabel4 = new JLabel();
			jLabel4.setText("Stok");
			GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
			gridBagConstraints3.gridx = 0;
			gridBagConstraints3.anchor = GridBagConstraints.WEST;
			gridBagConstraints3.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints3.gridy = 3;
			jLabel3 = new JLabel();
			jLabel3.setText("Ketegori");
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.gridx = 0;
			gridBagConstraints2.anchor = GridBagConstraints.WEST;
			gridBagConstraints2.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints2.gridy = 2;
			jLabel2 = new JLabel();
			jLabel2.setText("Harga");
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.gridx = 0;
			gridBagConstraints1.anchor = GridBagConstraints.WEST;
			gridBagConstraints1.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints1.gridy = 1;
			jLabel1 = new JLabel();
			jLabel1.setText("Nama");
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = 0;
			gridBagConstraints.anchor = GridBagConstraints.WEST;
			gridBagConstraints.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints.gridy = 0;
			jLabel = new JLabel();
			jLabel.setText("ID Barang");
			jContentPane = new JPanel();
			jContentPane.setLayout(new GridBagLayout());
			jContentPane.add(jLabel, gridBagConstraints);
			jContentPane.add(jLabel1, gridBagConstraints1);
			jContentPane.add(jLabel2, gridBagConstraints2);
			jContentPane.add(jLabel3, gridBagConstraints3);
			jContentPane.add(jLabel4, gridBagConstraints4);
			jContentPane.add(getTxtId(), gridBagConstraints5);
			jContentPane.add(getTxtNama(), gridBagConstraints6);
			jContentPane.add(getTxtHarga(), gridBagConstraints7);
			jContentPane.add(getTxtKategori(), gridBagConstraints11);
			jContentPane.add(getTxtStok(), gridBagConstraints21);
			jContentPane.add(getBtnSave(), gridBagConstraints31);
			jContentPane.add(getBtnCancel(), gridBagConstraints41);
		}
		return jContentPane;
	}

	/**
	 * This method initializes txtId
	 *
	 * @return javax.swing.JTextField
	 */
	private JTextField getTxtId() {
		if (txtId == null) {
			txtId = new JTextField();
			txtId.setColumns(10);
		}
		return txtId;
	}

	/**
	 * This method initializes txtNama
	 *
	 * @return javax.swing.JTextField
	 */
	private JTextField getTxtNama() {
		if (txtNama == null) {
			txtNama = new JTextField();
			txtNama.setColumns(15);
		}
		return txtNama;
	}

	/**
	 * This method initializes txtHarga
	 *
	 * @return javax.swing.JTextField
	 */
	private JTextField getTxtHarga() {
		if (txtHarga == null) {
			txtHarga = new JTextField();
			txtHarga.setColumns(10);
		}
		return txtHarga;
	}

	/**
	 * This method initializes txtKategori
	 *
	 * @return javax.swing.JTextField
	 */
	private JTextField getTxtKategori() {
		if (txtKategori == null) {
			txtKategori = new JTextField();
			txtKategori.setColumns(15);
		}
		return txtKategori;
	}

	/**
	 * This method initializes txtStok
	 *
	 * @return javax.swing.JTextField
	 */
	private JTextField getTxtStok() {
		if (txtStok == null) {
			txtStok = new JTextField();
			txtStok.setColumns(10);
		}
		return txtStok;
	}

	/**
	 * This method initializes btnSave
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBtnSave() {
		if (btnSave == null) {
			btnSave = new JButton();
			btnSave.setText("Save");
			btnSave.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					save();
				}
			});
		}
		return btnSave;
	}

	private void save() {
		BarangBean bean = new BarangBean();
		bean.setId(Integer.parseInt(txtId.getText()));
		bean.setNama(txtNama.getText());
		bean.setHarga(Double.parseDouble(txtHarga.getText()));
		bean.setKategori(txtKategori.getText());
		bean.setStok(Integer.parseInt(txtStok.getText()));

		String sql = "";
		if (newBean) {
			sql = "INSERT INTO MASTER_BARANG (N_ID, S_NAMA, N_HARGA, S_KATEGORI, N_STOK)" +
					" VALUES ("+bean.getId()+",'"+bean.getNama()+"',"+
					bean.getHarga()+",'"+bean.getKategori()+"',"+bean.getStok()+")";
		}
		else {
			sql = "UPDATE MASTER_BARANG SET S_NAMA = '"+bean.getNama()+"',"+
					"N_HARGA = "+bean.getHarga()+", S_KATEGORI = '"+bean.getKategori()+
					"', N_STOK = "+bean.getStok()+
					" WHERE N_ID = "+bean.getId();
		}

		parent.getManager().executeUpdate(sql);
		parent.refresh();
		dispose();
	}

	/**
	 * This method initializes btnCancel
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBtnCancel() {
		if (btnCancel == null) {
			btnCancel = new JButton();
			btnCancel.setText("Cancel");
			btnCancel.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					dispose();
				}
			});
		}
		return btnCancel;
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"

Class EditorDialog ini menerima input dari MainFrame berupa object BarangBean. Jika object tersebut null, akan dibuat object BarangBean baru. Jika tidak null, maka EditorDialog akan menampilkan property-property yang dimiliki oleh object BarangBean tersebut ke dalam masing-masing textfield yang berkaitan. Jika tombol save ditekan, EditorDialog akan mengupdate object BarangBean yang dengan nilai yang yang ada pada textfield. Jika object ini adalah object baru, maka akan dilakukan operasi insert. Jika EditorDialog berada pada mode edit, maka akan dilakukan operasi update.

Advertisements

August 21, 2008 - Posted by | Database, Java | , ,

12 Comments »

  1. mantaff bro..
    tq so much πŸ˜€

    Comment by newcahndeso | September 21, 2008 | Reply

  2. waduh masih bingung ne..abis baru blajar java..mohon bimbingannya..

    Comment by atan | January 5, 2009 | Reply

  3. MAs mau tanya ni cara muter mp3/wav di java bagaimana ya??
    dah googling n baca manualnya tapi masi mumet mas..
    trims banyak

    Comment by sayur | February 22, 2009 | Reply

  4. thank you, sangat berguna guidenya, ini dia yg saya perlukan..

    Comment by stanley | September 2, 2009 | Reply

  5. mas fungsi dari amp;amp;amp;amp;amp;amp;gt
    pada baris dibawah ini, apa y:

    for (int i=table.getRowCount()-1; i>=0; i–) {

    Terima kasih

    Comment by hendra | July 6, 2010 | Reply

    • Sorry, itu maksudnya tanda lebih besar. Sudah saya perbaiki.
      Thanks koreksinya πŸ™‚

      Comment by suhearie | July 6, 2010 | Reply

  6. halo, mau tanya dong πŸ™‚

    // connection url, format [protokol]://[hostname]/[databasename]

    private String dbUrl = “jdbc:mysql://localhost/myblog”;

    connection url itu dapet dari mana ya? karna aku nga biasa pake MySQL yg workbench nya.. aku selalu dr cmd.. tolong dijelasin ya πŸ™‚

    Comment by Mutia Dhuhanovitri | October 30, 2010 | Reply

  7. keren gan blognya.
    ini ane BM dl, besok pagi ane baca.skrn lagi kuliah.besok mohn dibimbing karena ane masih nubi banget:(

    Comment by vb | November 25, 2010 | Reply

    • Thanks gan, silahkan, silahkan..

      Comment by suhearie | November 26, 2010 | Reply

  8. Bg mau nanya,,,,, gimana cara mengkoneksikan database jdbc mysql yang telah ada,,,,,,sehingga pada saat di run tampil line chart dan data tersimpan di database
    khususnya untuk membuat line Chart,,,,,
    tlong di blz,,,,

    Comment by Pandan Ayunovia | January 31, 2013 | Reply


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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: