【13】shell:計算器
技術標籤:筆記
關鍵字: jtable操作資料庫實現增刪改 最近需要使用JTa
JTable實現資料庫的操作完整版 - 馬爾斯 - 私人空間的部落格
ble,第一次使用,很多不懂,到網上找了很多資料和例子,發現很多例子都沒有完全的實現操作資料庫裡一張表的資料,摸了兩天終於懂了一點,寫了一個例子,把程式碼直接複製,修改一下資料庫的連線就可以運行了.使用JTable操作資料庫的一張表,實現增刪改,顯示錶裡所有的資料,點選’‘新增’'按鈕在表格插入一行填寫資料儲存到資料庫,可一次插入多行,一次可選擇任意多行進行刪除,一次可以修改多行的值.有寫得不好的地方希望大家指出,一起進步.
共九個類:
一:
package product;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class ProductTableModel extends AbstractTableModel {
/**
- 神戀科技:http://suhuanxi.javaeye.com
*/
/**changeList用來存放被修改過的資料值,這樣做是為了一次修改多行多值, - 儲存的物件是ChangedProduct,只記錄被修改過的值.
private static List changeList = new ArrayList();
private List list = new ArrayList();
private String[] column = { “Product_id”, “Product Name”,
“Product Description”, “Status” };
public ProductTableModel() {
}
public ProductTableModel(List list) {
this();
setList(list);
}
public int getColumnCount() {
}
public int getRowCount() {
return list.size();
}
/**
- getValueAt方法就是使得資料在Table顯示出來,給每個單元格設值
*/
public Object getValueAt(int arg0, int arg1) {
ProductBean p = (ProductBean) list.get(arg0);
return getPropertyValueByCol(p, arg1);
}
public void addRow(int index, ProductBean p) {
if (index < 0 || index > list.size() - 1) {
list.add§;
fireTableRowsInserted(list.size(), list.size());
} else {
list.add(index + 1, p);
fireTableRowsInserted(index, index);
}
}
public boolean deleteRow(int index) {
if (index >= 0 && index < list.size()) {
list.remove(index);
fireTableRowsDeleted(index, index);
return true;
} else
return false;
}
public boolean saveRow(int index, ProductBean p) {
if (index >= 0 && index < list.size()) {
list.set(index, p);
fireTableRowsUpdated(index, index);
return true;
} else
return false;
}
public ProductBean getRow(int index) {
if (index >= 0 && index < list.size()) {
return (ProductBean) list.get(index);
} else
return null;
}
public List getNewRow(){
List list=new ArrayList();
List listProduct=getList();
Iterator it=listProduct.iterator();
while(it.hasNext()){
ProductBean p=new ProductBean();
p=(ProductBean)it.next();
if(p.getProduct_id()==0){
list.add§;
}
}
return list;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
fireTableDataChanged();
}
public String getColumnName(int i) {
return column[i];
}
public void setColumn(String[] column) {
this.column = column;
}
public Object getPropertyValueByCol(ProductBean p, int col) {
switch (col) {
case 0:
return p.getProduct_id();
case 1:
return p.getProduct_name();
case 2:
return p.getProduct_desc();
case 3:
return p.getProduct_status();
}
return null;
}
public void setPropertyValueByCol(ProductBean p, String value, int col) {
switch (col) {
case 1:
p.setProduct_name(value);
break;
case 2:
p.setProduct_desc(value);
break;
case 3:
p.setProduct_status(value);
break;
}
fireTableDataChanged();
}
public boolean isCellEditable(int row, int column) {
return true;
}
/**
- setValueAt方法是使增加或修改值的時候生效,aValue就是你在單元格填的值,
- 要把這些值儲存到資料來源中
*/
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
ProductBean p = (ProductBean) list.get(rowIndex);
setPropertyValueByCol(p, aValue.toString(), columnIndex);
this.fireTableCellUpdated(rowIndex, columnIndex);
}
public static List getChangeList() {
return changeList;
}
public static void setChangeList(List changeList) {
ProductTableModel.changeList = changeList;
}
}
二:
package product;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableColumnModel;
public class ProductFrame extends JFrame {
/**
- 神戀科技:http://suhuanxi.javaeye.com
*/
private JPanel panelTop = null;
private JLabel labHeader = null;
private JPanel panelBottom = null;
private JButton add = null;
private JButton delete = null;
private JButton save = null;
private JScrollPane scroll = null;
private JTable table = null;
private ProductTableModel model = null;
private List listProduct = null;
public ProductTableModel getModel() {
if (null == model) {
model = new ProductTableModel(listProduct);
//給model新增一個監聽,當修改的時候將觸發該事件,代表事件的類是ChangeEvent
model.addTableModelListener(new ChangeEvent(model));
return model;
}
return model;
}
public JLabel getLabHeader() {
if (null == labHeader) {
labHeader = new JLabel(“Maintaince Product Information”);
return labHeader;
}
return labHeader;
}
public JTable getTable() {
if (null == table) {
table = new JTable(getModel());
table.setEnabled(true);
table.setRowSelectionAllowed(true);
table.setBackground(Color.YELLOW);
/**
* 隱藏第一列ID,不顯示出來
*/
DefaultTableColumnModel dcm = (DefaultTableColumnModel)table.getColumnModel();
dcm.getColumn(0).setMinWidth(0);
dcm.getColumn(0).setMaxWidth(0);
return table;
}
return table;
}
public JScrollPane getPanTable() {
if (null == scroll) {
scroll = new JScrollPane();
scroll.setViewportView(getTable());
return scroll;
}
return scroll;
}
public JPanel getPanelTop() {
if (null == panelTop) {
panelTop = new JPanel();
panelTop.setLayout(new FlowLayout(FlowLayout.CENTER));
panelTop.add(getLabHeader());
return panelTop;
}
return panelTop;
}
public JPanel getPanelBottom() {
if (null == panelBottom) {
panelBottom = new JPanel();
panelBottom.setLayout(new FlowLayout(FlowLayout.CENTER));
panelBottom.add(getAdd());
panelBottom.add(getDelete());
panelBottom.add(getSave());
return panelBottom;
}
return panelBottom;
}
public JButton getAdd() {
/**
- 點該按鈕的時候呼叫addProduct()方法,在資料來源(listProduct)將
- 增加一個元素,沒設值前都是null.
*/
if (null == add) {
add = new JButton(“New”);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addProduct();
}
});
return add;
}
return add;
}
public JButton getDelete() {
if (null == delete) {
delete = new JButton(“Delete”);
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/**
* 支援一次選中多行後刪除
*/
int[] rows=getTable().getSelectedRows();
if(rows.length>0){
int flag=JOptionPane.showConfirmDialog(null, “確定刪除?”);
if(flag==JOptionPane.YES_OPTION)
deleteProduct();
}
else
JOptionPane.showMessageDialog(null,“請選擇要刪除的行!”);
}
});
return delete;
}
return delete;
}
public JButton getSave() {
if (null == save) {
save = new JButton(“save”);
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveProduct();
JOptionPane.showMessageDialog(null,“更新成功!”);
}
});
return save;
}
return save;
}
public void addProduct() {
ProductBean p = new ProductBean();
getModel().addRow(getTable().getSelectedRow(), p);
}
public void saveProduct() {
DaoInterface dao=DaoFactory.getDao();
List changeList=getModel().getChangeList();
//如果有修改過就呼叫update方法
if(changeList.size()>0){
dao.update(changeList);
changeList.clear();
}
List newRow=getModel().getNewRow();
//如果是新增就呼叫saveList,支援一次增加多行
if(newRow.size()>0){
dao.saveList(newRow);
getModel().setList(dao.getList());
getTable().updateUI();
newRow.clear();
}
}
public void deleteProduct() {
/**支援一次刪除多行,先獲得所有選中的行,然後按照行數取得Product例項,
- 放進一個list,然後傳給操作資料庫的deleteList方法.
/
int[] rows=getTable().getSelectedRows();
ArrayList list=new ArrayList();
DaoInterface dao=DaoFactory.getDao();
for(int i=rows.length-1;i>=0;i–){
list.add(getModel().getRow(rows[i]));
getModel().deleteRow(rows[i]);
}
dao.deleteList(list);
getTable().updateUI();
list.clear();
}
public void initData() {
/* - 初始化資料來源,從資料庫裡把資料拿出來,然後它會呼叫
- getValueAt方法來一個單元格一個單元格來設值,讓它顯示出來.
*/
listProduct = new ArrayList();
DaoInterface dao=DaoFactory.getDao();
listProduct=dao.getList();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public ProductFrame() {
initData();
Container c = this.getContentPane();
c.setLayout(new BorderLayout());
c.add(getPanelTop(), BorderLayout.NORTH);
c.add(getPanelBottom(), BorderLayout.SOUTH);
c.add(getPanTable(), BorderLayout.CENTER);
this.setSize(new Dimension(600, 400));
this.setVisible(true);
}
public static void main(String[] args) {
ProductFrame frame = new ProductFrame();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
三:
package product;
public class ProductBean {
/**
- 神戀科技:http://suhuanxi.javaeye.com
*/
private int product_id;
private String product_name;
private String product_desc;
private String product_status;
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_desc() {
return product_desc;
}
public void setProduct_desc(String product_desc) {
this.product_desc = product_desc;
}
public String getProduct_status() {
return product_status;
}
public void setProduct_status(String product_status) {
this.product_status = product_status;
}
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
}
四:
package product;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBConnection {
/**
-
神戀科技:http://suhuanxi.javaeye.com
*/
private static Connection conn;
public static Connection getConn() {
String driverName = “oracle.jdbc.driver.OracleDriver”;
String url = “jdbc:oracle:thin:@192.168.0.66:1521:test”;
String userName = “JACKTRAINING”;
String pwd = “JACKTRAINING”;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url, userName, pwd);
} catch (ClassNotFoundException e) {
System.out.println(“裝載驅動出錯!”);
} catch (SQLException e) {
System.out.println(“獲取資料庫連接出錯!”);
e.printStackTrace();
}return conn;
}
}
五:
package product;
import java.util.ArrayList;
import java.util.List;
public interface DaoInterface {
/**
- 神戀科技:http://suhuanxi.javaeye.com
*/
public List getList();
public void saveList(List list);
public void deleteList(List list);
public void update(List list);
}
六:
package product;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
public class DaoImpl implements DaoInterface {
/**
*/
public List getList() {
Connection conn = JDBConnection.getConn();
String s1 = “select * from justin_jtable_product order by product_id asc”;
PreparedStatement ps = null;
ResultSet rs = null;
List list = new ArrayList();
try {
ps = conn.prepareStatement(s1);
rs = ps.executeQuery();
} catch (SQLException e) {
System.out.println(“取出全部資料出錯!”);
JOptionPane.showMessageDialog(null, “取出全部資料出錯!”);
e.printStackTrace();
}
try {
while (rs.next()) {
ProductBean p = new ProductBean();
p.setProduct_id(rs.getInt(1));
p.setProduct_name(rs.getString(2));
p.setProduct_desc(rs.getString(3));
p.setProduct_status(rs.getString(4));
list.add§;
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, “取出全部資料出錯!”);
e.printStackTrace();
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, “關閉資料連線時出錯!”);
e.printStackTrace();
}
}
return list;
}
public void saveList(List list) {
String s1 = “”;
Connection conn = JDBConnection.getConn();
PreparedStatement ps = null;
try {
Iterator it = list.iterator();
while (it.hasNext()) {
ProductBean p = (ProductBean) it.next();
String name = p.getProduct_name();
String desc = p.getProduct_name();
String status = p.getProduct_status();
int id = p.getProduct_id();
s1 = “insert into justin_jtable_product(product_name,”
+ “product_desc,product_status) values(?,?,?)”;
ps = conn.prepareStatement(s1);
ps.setString(1, name);
ps.setString(2, desc);
ps.setString(3, status);
ps.executeUpdate();
}
} catch (SQLException e) {
System.out.println(“新增資料時出錯!”);
JOptionPane.showMessageDialog(null, “新增資料時出錯!”);
e.printStackTrace();
} finally {
try {
ps.close();
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, “關閉資料連線時出錯!”);
e.printStackTrace();
}
}
}
public void deleteList(List list) {
String str = “delete from justin_jtable_product where product_id=?”;
int id = 0;
Iterator it = list.iterator();
Connection conn = JDBConnection.getConn();
PreparedStatement ps = null;
try {
while (it.hasNext()) {
id = ((ProductBean) it.next()).getProduct_id();
ps = conn.prepareStatement(str);
ps.setInt(1, id);
ps.executeUpdate();
}
} catch (SQLException e) {
} finally {
try {
ps.close();
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, “關閉資料連線時出錯!”);
e.printStackTrace();
}
}
}
public void update(List list) {
Connection conn = JDBConnection.getConn();
PreparedStatement ps = null;
Iterator it = list.iterator();
int id = 0;
int col = 0;
String value = “”;
String str = “”;
try {
while (it.hasNext()) {
ChangedProduct ch = (ChangedProduct) it.next();
id = ch.getId();
col = ch.getCol();
value = ch.getValue();
switch (col) {
case 1:
str = “update justin_jtable_product set product_name=? where product_id=?”;
break;
case 2:
str = “update justin_jtable_product set product_desc=? where product_id=?”;
break;
case 3:
str = “update justin_jtable_product set product_status=? where product_id=?”;
}
ps = conn.prepareStatement(str);
ps.setString(1, value);
ps.setInt(2, id);
ps.executeUpdate();
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, “修改資料時出錯!”);
e.printStackTrace();
} finally {
try {
ps.close();
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, “關閉資料連線時出錯!”);
e.printStackTrace();
}
}
}
}
七:
package product;
public class DaoFactory {
/**
- 神戀科技:http://suhuanxi.javaeye.com
*/
synchronized public static DaoInterface getDao(){
DaoInterface dao=null;
if(dao==null){
dao=new DaoImpl();
return dao;
}
return dao;
}
}
八:
package product;
public class ChangedProduct {
/**
*/
private int id;
private int col;
private String value;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getCol() {
return col;
}
public void setCol(int col) {
this.col = col;
}
}
九:
package product;
import java.util.ArrayList;
import java.util.List;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
public class ChangeEvent implements TableModelListener {
/**
/
/*
- 監聽table被改動的事件,只要目的是用來記錄被修改過的值,
- 這樣做可以一次任意行的修改值,修改一個單元格的值就記錄一次,
- 主要記錄id,新值,烈數.
*/
ProductTableModel model = null;
public ChangeEvent(ProductTableModel model) {
this.model = model;
}
List list = model.getChangeList();
int id = 0;
String value = “”;
public void tableChanged(TableModelEvent arg0) {
int row = arg0.getFirstRow();
int col = arg0.getColumn();
if (col != -1) {
ChangedProduct cp = new ChangedProduct();
id = ((Integer) model.getValueAt(row, 0)).intValue();
if (id != 0) {
value = model.getValueAt(row, col).toString();
cp.setId(id);
cp.setCol(col);
cp.setValue(value);
list.add(cp);
}
}
}
}
文章最後釋出於: 2011-06-01## 標題