Skip to content

Instantly share code, notes, and snippets.

@arbo77
Created September 20, 2012 10:47
Show Gist options
  • Save arbo77/3755175 to your computer and use it in GitHub Desktop.
Save arbo77/3755175 to your computer and use it in GitHub Desktop.
Simple Java fetching MySQL records into DefaultTableModel
class frmGuiFetch {
public static void main(String[] args)
{
guiFetch f = new guiFetch();
f.setVisible(true);
}
}
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.table.*;
class guiFetch extends JFrame {
Connection cn;
Statement stmt;
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
private JButton btnTutup = new JButton("Tutup");
private JButton btnProses = new JButton("Proses");
public guiFetch(){
setTitle("Table Grid");
setSize(350,300);
setLocation(new Point(250,250));
setLayout(null);
setResizable(false);
JScrollPane scroll = new JScrollPane(table);
scroll.setBounds(20,60,320,200);
btnTutup.setBounds(20,20,100,20);
btnProses.setBounds(200,20,100,20);
add(btnTutup);
add(btnProses);
add(scroll);
model.addColumn("X");
model.addColumn("Y");
model.addColumn("Z");
initDb();
initTable();
event();
}
public void initDb(){
try {
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/test",
"root",
"toor");
stmt = cn.createStatement();
} catch (Exception ex) {
System.err.println(ex);
}
}
public void initTable(){
try {
while (model.getRowCount()>0){
model.removeRow(0);
}
ResultSet rs = stmt.executeQuery("SELECT * FROM test");
while(rs.next()){
model.addRow(new Object[]{
rs.getString("x"),
rs.getString("y"),
rs.getString("z")});
}
}catch (Exception ex) {
System.err.println(ex);
}
}
private void event(){
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
try{
cn.close();
}catch (Exception ex) {
System.err.println(ex);
}
System.exit(1);
}
});
btnTutup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnTutupClick(e);
}
});
btnProses.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnProsesClick(e);
}
});
}
private void btnTutupClick(ActionEvent evt){
System.exit(1);
}
private void btnProsesClick(ActionEvent evt){
try{
String sql;
sql = "INSERT INTO test VALUES (0,'X',CURRENT_TIMESTAMP)";
stmt.execute(sql);
initTable();
}catch (Exception ex) {
System.err.println(ex);
}
}
}
-- sample test table
CREATE TABLE `test` (
`x` int(11) NOT NULL AUTO_INCREMENT,
`y` varchar(10) DEFAULT NULL,
`z` datetime DEFAULT NULL,
PRIMARY KEY (`x`)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment