1.首先我们建立一个产品类,这里我用product 然后建立他的构造方法和getter and setter方法,重写 equals方法
package Table;
import java.sql.Date;
public class product {
/** 商品编号*/
private String productID;
/** 商品名称*/
private String productName;
/** 安全存量*/
private float safeStock;
/** 最后进货日期*/
private Date lastPurchaseDate;
/** 最后销售日期*/
private Date lastDeliveryDate;
/** 当前数量*/
private float quantity;
/** 建议购买价*/
private float suggestBuyPrice;
/** 建议销售价*/
private float suggestSalePrice;
public product() {
super();
}
@Override
public boolean equals(Object arg0) {
if( arg0 instanceof product){
product p=(product) arg0;
if(p.productID.equals(this.productID))
return true;
}
return false;
}
public String getProductID() {
return productID;
}
public void setProductID(String productID) {
this.productID = productID;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getSafeStock() {
return safeStock;
}
public void setSafeStock(float safeStock) {
this.safeStock = safeStock;
}
public Date getLastPurchaseDate() {
return lastPurchaseDate;
}
public void setLastPurchaseDate(Date lastPurchaseDate) {
this.lastPurchaseDate = lastPurchaseDate;
}
public Date getLastDeliveryDate() {
return lastDeliveryDate;
}
public void setLastDeliveryDate(Date lastDeliveryDate) {
this.lastDeliveryDate = lastDeliveryDate;
}
public float getQuantity() {
return quantity;
}
public void setQuantity(float quantity) {
this.quantity = quantity;
}
public float getSuggestBuyPrice() {
return suggestBuyPrice;
}
public void setSuggestBuyPrice(float suggestBuyPrice) {
this.suggestBuyPrice = suggestBuyPrice;
}
public float getSuggestSalePrice() {
return suggestSalePrice;
}
public void setSuggestSalePrice(float suggestSalePrice) {
this.suggestSalePrice = suggestSalePrice;
}
}
2.我们放置一个list来事先加载我们在数据库中的东西
package Table;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class productlist {
Connection conn=null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<product> ar=new ArrayList<product>();
product product=new product();
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=ELMS;";//声明端口和数据库名字
String sql = "select * from Product";//sql查询语句;
public productlist(){
ar=getAllworh();//先把数据库中的数据传输出来给ar;
}
public ArrayList getAllworh() {//取得数据库中的数据放到ArrayList中
ArrayList<product> ar=new ArrayList<product>();
getconn();//链接数据库
if(conn!=null) {
try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);//执行语句
product p;
while(rs.next()) {
p=new product();
p.setProductID(rs.getString(1));
p.setProductName(rs.getString(2));
p.setSafeStock(rs.getFloat(3));
p.setLastPurchaseDate(rs.getDate(4));
p.setLastDeliveryDate(rs.getDate(5));
p.setQuantity(rs.getFloat(6));
p.setSuggestBuyPrice(rs.getFloat(7));
p.setSuggestSalePrice(rs.getFloat(8));
ar.add(p);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return ar;
}
public Object[][] listToArray(){//给数组赋值,方便表格操作
Object[][] ps=new Object[100][8];
Object[] os= ar.toArray();
for(int i=0;i<os.length;i++){
ps[i][0]=((product)os[i]).getProductID();
ps[i][1]=((product)os[i]).getProductName();
ps[i][2]=((product)os[i]).getSafeStock();
ps[i][3]=((product)os[i]).getSuggestBuyPrice();
ps[i][4]=((product)os[i]).getSuggestSalePrice();
ps[i][5]=((product)os[i]).getQuantity();
ps[i][6]=((product)os[i]).getLastPurchaseDate();
ps[i][7]=((product)os[i]).getLastDeliveryDate();
// product p=(product)os[i];
// ps[i][0]=p.getProductID();
// ps[i][1]=p.getProductName();
// ps[i][2]=p.getSafeStock();
// ps[i][3]=p.getSuggestBuyPrice();
// ps[i][4]=p.getSuggestSalePrice();
// ps[i][5]=p.getQuantity();
// ps[i][6]=p.getLastPurchaseDate();
// ps[i][7]=p.getLastDeliveryDate();
}
return ps;
}
public void getconn() {//链接数据库,我这链接的SQL server
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//根据数据库的不同,这行代码都不同,在网上都能找到↑↑↑
conn = DriverManager.getConnection(url, "sa", "135831");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.我将监听和图形互化界面放在了一起,我在代码中阐述作用
package Table;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.xml.crypto.Data;
public class Table extends JFrame implements ActionListener,MouseListener{
//继承了Jframe ,一个监听,一个鼠标监听
int i;
JTable table;//表格
Object a[] [];//二维数组a
Object[] title={"商品编号","商品名称","安全存量","建议购买价",
"建议销售价","当前数量","最后进货日期","最后送货日期"};//表头
productlist pl=new productlist();
JTextField JTproductID,JTproductName,JTsafeStock,JTlastPurchaseDate,JTlastDeliveryDate,
JTquantity,JTsuggestBuyPrice,JTsuggestSalePrice;
JButton AddButton,Moifty,Delete,Select;//设置一下
Font Mfont=new Font("幼圆",Font.BOLD,14);//设置字体
Color Mcolor=new Color(240,0,0);//设置颜色
public Table(){
setTitle("商品管理系统");//标题
setBounds(350, 150, 700, 750);//大小
setVisible(true);//可见
setDefaultCloseOperation(DISPOSE_ON_CLOSE);//关闭形式
setLayout(new BorderLayout());//设置布局为border
a=pl.listToArray();//将一维数组转换成二维数组
table=new JTable(a,title);//新建一个表格将二位数组和表头数组放进去
add(table,BorderLayout.NORTH);
JPanel J1=new JPanel();//建立一个面板
JTproductID=new JTextField(10);//建立每个属性的TextField
JTproductName=new JTextField(10);
JTsafeStock=new JTextField(10);
JTlastPurchaseDate=new JTextField(10);
JTlastDeliveryDate=new JTextField(10);
JTquantity=new JTextField(10);
JTsuggestBuyPrice=new JTextField(10);
JTsuggestSalePrice=new JTextField(10);
Label la1=new Label("商品编号:");//显示文字的label
Label la2=new Label("商品名称:");
Label la3=new Label("安全存量:");
Label la4=new Label("建议购买价:");
Label la5=new Label("建议销售价:");
Label la6=new Label("当前数量:");
Label la7=new Label("最后进货日期:");
Label la8=new Label("最后送货日期:");
la1.setForeground(Mcolor);//字体设置颜色
la2.setForeground(Mcolor);
la3.setForeground(Mcolor);
la4.setForeground(Mcolor);
la5.setForeground(Mcolor);
la6.setForeground(Mcolor);
la7.setForeground(Mcolor);
la8.setForeground(Mcolor);
J1.add(la1);//将文字label和TextField按照顺序放到JPanel中
J1.add(JTproductID);
J1.add(la2);
J1.add(JTproductName);
J1.add(la3);
J1.add(JTsafeStock);
J1.add(la4);
J1.add(JTsuggestBuyPrice);
J1.add(la5);
J1.add(JTsuggestSalePrice);
J1.add(la6);
J1.add(JTquantity);
J1.add(la7);
J1.add(JTlastPurchaseDate);
J1.add(la8);
J1.add(JTlastDeliveryDate);
add(J1,BorderLayout.CENTER);//将j1 JPanel放到BorderLayout中间
JPanel J2=new JPanel();//新建JPanel J2 用来放置按钮
AddButton=new JButton("新增");
Delete=new JButton("删除");
Select=new JButton("查找");
Moifty=new JButton("修改");
AddButton.setFont(Mfont);//设置一下字体格式
Delete.setFont(Mfont);
Select.setFont(Mfont);
Moifty.setFont(Mfont);
J2.add(AddButton);
J2.add(Delete);
J2.add(Select);
J2.add(Moifty);
add(J2,BorderLayout.SOUTH);//将J2放到BorderLayout的南部(下方)
Box box =Box.createVerticalBox();//新建一个盒子
box.add(new JScrollPane(table));//放入Table (JScrollPane(滚动面板))
box.add(J1);//放入J1
box.add(J2);//放入J2
add(box);//加入盒子
AddButton.addActionListener(this);//添加各种监听
Delete.addActionListener(this);
table.addMouseListener(this);
Select.addActionListener(this);
Moifty.addActionListener(this);
validate();
}
public void SETtable() {
//更新表格
DefaultTableModel dtm = new DefaultTableModel();
dtm.setDataVector(a, title);
table.setModel(dtm);//设置表格模型
}
public static void main(String[] args) {
new Table();
}
@Override
public void actionPerformed(ActionEvent e) {
// SimpleDateFormat aaa=new SimpleDateFormat("yyyy-mm-dd");
// TODO Auto-generated method stub
if(e.getSource()==AddButton){
product pro=new product();//新建一个product对象,将JTextField中的数据放到该对象中
pro.setProductID(JTproductID.getText().trim());
pro.setProductName(JTproductName.getText().trim());
pro.setSafeStock(Float.parseFloat(JTsafeStock.getText().trim()));//Float类型用parseFloat类型转换一下
pro.setLastPurchaseDate(Date.valueOf(JTlastPurchaseDate.getText().trim()));//Date类型用Date.valueof类型转换一下
pro.setLastDeliveryDate(Date.valueOf(JTlastDeliveryDate.getText().trim()));
pro.setQuantity(Float.parseFloat(JTquantity.getText().trim()));
pro.setSuggestBuyPrice(Float.parseFloat(JTsuggestBuyPrice.getText().trim()));
pro.setSuggestSalePrice(Float.parseFloat(JTsuggestSalePrice.getText().trim()));
String sql="insert into Product (ProductID,ProductName, SafeStock,
LastPurchaseDate,LastDeliveryDate,Quantity,
SuggestBuyPrice,SuggestSalePrice) values(?,?,?,?,?,?,?,?)";
//“?” 是占位符,我们待会要往里添加数据
pl.getconn();//链接数据库
try {
PreparedStatement statement=pl.conn.prepareStatement(sql);
//准备一个PreparedStatement ,开始往里面赋值
statement.setString(1, pro.getProductID());
statement.setString(2, pro.getProductName());
statement.setFloat(3, pro.getSafeStock());
statement.setDate(4, pro.getLastDeliveryDate());
statement.setDate(5, pro.getLastPurchaseDate());
statement.setFloat(6, pro.getQuantity());
statement.setFloat(7, pro.getSuggestBuyPrice());
statement.setFloat(8, pro.getSuggestSalePrice());
int i=statement.executeUpdate();//执行更新 返回的是几行瘦影响
if(i==1) {//因为我们会影响一行,所以条件是i==1
System.out.println("添加成功");
}
else {
System.out.println("添加失败");
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
pl.ar=pl.getAllworh();//重新获取数据库中的数据
a=pl.listToArray();//将数组中的数据重新更新一遍
SETtable();
}
if(e.getSource()==Delete){
String sql="delete from Product where ProductID = ?";
pl.getconn();
try {
PreparedStatement statement=pl.conn.prepareStatement(sql);
String No=JTproductID.getText().trim();
//取得productID文本的文本,我们要用这个文本来查询整个物品↑↑
statement.setString(1,No);//给第一个赋值
int i=statement.executeUpdate();//执行语句
if(i==1) {
System.out.println("删除成功");
}
else {
System.out.println("删除失败");
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
pl.ar=pl.getAllworh();
a=pl.listToArray();
SETtable();
}
if(e.getSource()==Select) {
pl.getconn();
String sql="select *from Product where ProductID=?";
try {
PreparedStatement statement=pl.conn.prepareStatement(sql);
statement.setString(1, JTproductID.getText().trim());//设置搜索id
ResultSet rs=statement.executeQuery();
while (rs.next()) {//转换就用String.valueOf
JTproductID.setText((String)rs.getString(1));
JTproductName.setText((String)rs.getString(2));
JTsafeStock.setText(String.valueOf(rs.getString(3)));
JTsuggestBuyPrice.setText(String.valueOf(rs.getString(4)));
JTsuggestSalePrice.setText(String.valueOf(rs.getString(5)));
JTquantity.setText(String.valueOf(rs.getString(6)));
JTlastDeliveryDate.setText(String.valueOf(rs.getString(7)));
JTlastPurchaseDate.setText(String.valueOf(rs.getString(8)));
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(e.getSource()==Moifty) {
String sql= "update Product set ProductName=?,SafeStock=?,LastPurchaseDate=?,LastDeliveryDate=?,Quantity=?,SuggestBuyPrice=?,SuggestSalePrice=? where ProductID=?";
try {
PreparedStatement statement=pl.conn.prepareStatement(sql);
statement.setString(1, JTproductName.getText().trim());
statement.setString(2, JTsafeStock.getText().trim());
statement.setString(3, JTlastPurchaseDate.getText().trim());
statement.setString(4, JTlastDeliveryDate.getText().trim());
statement.setString(5, JTquantity.getText().trim());
statement.setString(6, JTsuggestBuyPrice.getText().trim());
statement.setString(7, JTsuggestSalePrice.getText().trim());
statement.setString(8, JTproductID.getText().trim());
int i=statement.executeUpdate();
if (i==1) {
System.out.println("修改成功");
}
else {
System.out.println("修改失败");
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
pl.ar=pl.getAllworh();
a=pl.listToArray();
SETtable();
}
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
i=table.getSelectedRow();//获取点击的第几行,将值复制给i
JTproductID.setText((String)a[i][0]);
JTproductName.setText((String)a[i][1]);
//两种方法都可赋值
String float1 = String.valueOf(table.getValueAt(i,2));
JTsafeStock.setText(float1+"");
JTsuggestBuyPrice.setText(String.valueOf(a[i][3]));
JTsuggestSalePrice.setText(String.valueOf(a[i][4]));
JTquantity.setText(String.valueOf(a[i][5]));
JTlastDeliveryDate.setText(String.valueOf(a[i][6]));
JTlastPurchaseDate.setText(String.valueOf(a[i][7]));
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
4.形成的界面
PS:注意如果赋值代码,包名Table ,自己修改自己的数据库名字,表名字,列的名字!