关键字: jtable操作数据库实现增删改 最近需要使用JTa
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() {
return column.length;
}
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(p);
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(p);
}
}
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(p);
}
} 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);
}
}
}
}