前言
作者是一个才学java的新手,水平比较低,见谅
而且这个小练习也是基于之前写过的一个练习修改而来(将数据存储获取全部改为利用MySQL)
本文的代码想要正常运行需要安装MySQL数据库并配置好环境,
而且在项目中需要添加JDBC驱动包,如下图:
以下是源代码
1.连接数据库
package DataBaseOperation;
/*
* 用于获取数据库连接
*/
import java.sql.*;
public class JDBCutil
{
private String Driver;//驱动
private String URL;//服务器地址,数据库名
private String USERNAME;//用户名
private String PASSWORD;//用户密码
private Connection connect;//数据库连接对象
public JDBCutil()
{
this.Driver = "com.mysql.jdbc.Driver";
//?useSSL=false加上这段,是因为如果不加会警告不建议连接没有带服务器身份验证的SSL(虽然无所谓,简单练习不需要纠结证书
this.URL = "jdbc:mysql://localhost:3306/express?useSSL=false";
this.USERNAME = "root";
this.PASSWORD = "这里输入你自己设置的密码";
}
public Connection getConnection()
{
try
{
Class.forName(this.Driver);//加载MySQL JDBC驱动程序
System.out.println("Success loading MySQL Driver");
}
catch(Exception e)
{
System.out.println("Error loading MySQL Driver");
e.printStackTrace();
}
try
{
this.connect = DriverManager.getConnection(this.URL, this.USERNAME, this.PASSWORD);//建立连接
System.out.println("Success connect MySQL server");
}
catch(Exception e)
{
System.out.println("Error connect MySQL server");
e.printStackTrace();
}
return this.connect;
}
/*public static void main(String[] args)
{
}*/
}
2.对数据进行操作
package DataBaseOperation;
/*
* 利用SQL语句对数据库进行操作
* 读取,插入,删除,更新
*/
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import Information.ExpressInformation;
public class SqlOperation
{
private Connection connect;//与数据库的连接
private PreparedStatement pstmt;//预编译SQL语句对象
private ResultSet rs;//pstmt返回的表结果集(pstmt关闭该类也自动关闭
private ArrayList<ExpressInformation> data;//用于存放读取的数据集
private JDBCutil util;//获取连接类
public SqlOperation()
{
this.util = new JDBCutil();
this.connect = this.util.getConnection();
this.data = new ArrayList<ExpressInformation>();
}
public ArrayList<ExpressInformation> getData()
{
return this.data;
}
//查询读取数据
public void Load()
{
//查询用的SQL语句
String SelectSQL = "SELECT *" + "FROM information";
try
{
this.pstmt = this.connect.prepareStatement(SelectSQL);//这个方法需要捕捉异常
this.rs = this.pstmt.executeQuery();//执行查询SQL语句,获得表的结果集
while(rs.next())
{
this.data.add(new ExpressInformation(rs.getString(1),rs.getInt(2),
rs.getString(3),rs.getString(4),
rs.getString(5),rs.getString(6)));//获得每一列的数据(和类的构造函数参数顺序对应)
}
this.rs.close();//立即释放该对象的JDBC和数据库资源
this.pstmt.close();//同上
}
catch(SQLException e)
{
System.out.println("Data load error");
e.printStackTrace();
}
}
//插入新的订单
public void Insert(ExpressInformation order)
{
//插入用的SQL语句
//初始化就需要设置的列(INSERT INTO后表名+列 ,要按顺序对应,占位符的数量也要相同,不然会产生越界错误
String InsertSQL = "INSERT INTO information(id,kind,sender,addressee,SendDate,ReceiveDate)"
+ "VALUES(?,?,?,?,?,?)";//?是占位符,必须在执行前通过setXXX方法进行设置
try
{
this.pstmt = this.connect.prepareStatement(InsertSQL);
//对应数据库中表的行的每一列,顺序不能错
//这些setXXXX方法都是设置之前预编译在pstmt中的SQL语句的占位符
this.pstmt.setString(1, order.getID());
this.pstmt.setInt(2, order.getKind());
this.pstmt.setString(3, order.getSender());
this.pstmt.setString(4, order.getAddressee());
this.pstmt.setString(5, order.getSendDate());
this.pstmt.setString(6, order.getReceiveDate());
this.pstmt.executeUpdate();//执行更新SQL语句,SQL更新语句是预编译在其中的
JOptionPane.showMessageDialog(null, "订单创建成功");//如果上句出现异常,将会跳过这句执行catch的提示
this.pstmt.close();
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null, "订单已存在");
e.printStackTrace();
}
}
public void Delete(String d_id)
{
//删除用的SQL语句,因为id用String型存储,WHERE筛选记得用' '括住传入的id变量
String DeleteSQL = "DELETE FROM information "+ "WHERE id = ?";
try
{
this.pstmt = this.connect.prepareStatement(DeleteSQL);
this.pstmt.setString(1, d_id);
this.pstmt.executeUpdate();
this.pstmt.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public void Updata(String u_id,String u_col)//修改订单的订单号和将要修改的列
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
String date = df.format(new Date());//获取当前日期
//更新数据用的SQL语句
//该SQL语句: 选择id为u_id(具体哪行看传递的参数)的行的u_col列(具体名称看传递的参数)修改其数据
String UpdataSQL = "UPDATE information SET "+ u_col+ "= ? WHERE id = ?";
try
{
this.pstmt = this.connect.prepareStatement(UpdataSQL);
this.pstmt.setString(1, date);
this.pstmt.setString(2, u_id);
this.pstmt.executeUpdate();
JOptionPane.showMessageDialog(null, "订单修改成功");//如果上句出现异常,将会跳过这句执行catch的提示
this.pstmt.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
/*public static void main(String[] args)
{
SqlOperation s = new SqlOperation();
ExpressInformation e;
e = new ExpressInformation("37",2,"信息","订单","","");
//s.Insert(e);
s.Delete("37");
//s.Updata("17","SendDate");
s.Load();
for(Iterator<ExpressInformation> it = s.getData().iterator();
it.hasNext();)
{
e = it.next();
System.out.println(e.getID());
System.out.println(e.getAddressee());
System.out.println(e.getSendDate());
}
}*/
}
3.主菜单界面
package System;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/*
* 主菜单界面,可以选择读取订单,修改订单,创建新订单等
*/
@SuppressWarnings("serial")
public class MainMenu extends JFrame implements ActionListener
{
JButton creat,query,modify,exit;//创建,查询,修改,退出
JLabel title;//用于写标题的标签
JPanel jp1,jp2,jp3,jp4,jp5 = null;
public MainMenu()
{
//容器初始化
this.jp1 = new JPanel();
this.jp2 = new JPanel();
this.jp3 = new JPanel();
this.jp4 = new JPanel();
this.jp5 = new JPanel();
//按钮初始化
this.creat = new JButton("创建新订单");
this.query = new JButton("查询订单");
this.modify = new JButton("修改订单");
this.exit = new JButton("退出");
//为按钮添加监听事件
this.creat.addActionListener(this);
this.query.addActionListener(this);
this.modify.addActionListener(this);
this.exit.addActionListener(this);
//标签初始化
this.title = new JLabel("大学生快递管理系统");
//将组件装入容器
this.jp1.add(title);
this.jp2.add(creat);
this.jp3.add(query);
this.jp4.add(modify);
this.jp5.add(exit);
//将所有容器装入面板
this.add(jp1);
this.add(jp2);
this.add(jp3);
this.add(jp4);
this.add(jp5);
//面板属性设置
this.setLayout(new GridLayout(5,1));
this.setTitle("大学生快递管理系统");
this.setSize(350,250);
this.setLocation(700, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand() == "创建新订单")
{
this.dispose();
CreatNewOrder creat_UI = new CreatNewOrder();//打开创建订单对象
}
else if(e.getActionCommand() == "查询订单")
{
this.dispose();
QueryData query_UI = new QueryData();
}
else if(e.getActionCommand() == "修改订单")
{
this.dispose();
ModifyOrder modify_UI = new ModifyOrder();
}
else if(e.getActionCommand() == "退出")
{
this.dispose();
}
}
public static void main(String[] args)
{
MainMenu test = new MainMenu();
// TODO Auto-generated method stub
}
}
4.创建订单界面
添加的新订单在数据库中查看
package System;
import Information.ExpressInformation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import DataBaseOperation.*;
import javax.swing.*;
/*
* 创建新订单界面的GUI和创建新订单的方法
*/
public class CreatNewOrder extends JFrame implements ActionListener
{
JPanel jp1,jp2,jp3,jp4,jp5;//四个面板,用来放置标签等元素
JLabel id_l, sender_l, addressee_l;//标签
JTextField id_t, sender_t, addressee_t;//输入快递ID,寄送人,收件人信息的文本框
JRadioButton urgent, ordinary;//加急和普通件选项按钮
JButton clear, confirm, back;//清空文本框,确认,返回上一个页面选项
ButtonGroup bg; //按钮群组,放置快递类别按钮
public CreatNewOrder()
{
//面板初始化
this.jp1 = new JPanel();
this.jp2 = new JPanel();
this.jp3 = new JPanel();
this.jp4 = new JPanel();
this.jp5 = new JPanel();
//标签创建
this.id_l = new JLabel("快递ID:");
this.sender_l = new JLabel("寄件人姓名:");
this.addressee_l = new JLabel("收件人姓名:");
//创建文本输入框
this.id_t = new JTextField(20);
this.sender_t = new JTextField(20);
this.addressee_t = new JTextField(20);
//快件分类选择按钮创建
this.urgent = new JRadioButton("加急");
this.ordinary = new JRadioButton("普通");
this.bg = new ButtonGroup();
this.bg.add(urgent);
this.bg.add(ordinary);
this.ordinary.setSelected(true);
//创建操作按钮
this.clear = new JButton("清空输入内容");
this.confirm = new JButton("确认创建订单");
this.back = new JButton("返回");
//将各类组件加入面板
this.jp1.add(id_l);
this.jp1.add(id_t);
this.jp2.add(sender_l);
this.jp2.add(sender_t);
this.jp3.add(addressee_l);
this.jp3.add(addressee_t);
this.jp4.add(urgent);
this.jp4.add(ordinary);
this.jp5.add(clear);
this.jp5.add(confirm);
this.jp5.add(back);
this.add(jp1);
this.add(jp2);
this.add(jp3);
this.add(jp4);
this.add(jp5);
//添加事件
this.clear.addActionListener(this);
this.back.addActionListener(this);
this.confirm.addActionListener(this);
this.setLayout(new GridLayout(5,1));//选择GridLayout布局管理器
this.setTitle("新订单创建");
this.setSize(700,250);
this.setLocation(600, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置当关闭窗口时,保证JVM也退出
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand() == "清空输入内容")
{
clear_text();
}
else if(e.getActionCommand() == "确认创建订单")
{
creat();
clear_text();
}
else if(e.getActionCommand() == "返回")
{
this.dispose();
MainMenu main_ui = new MainMenu();
}
}
public void clear_text()//清空所以JTextField中的数据
{
this.id_t.setText("");
this.sender_t.setText("");
this.addressee_t.setText("");
}
public void creat()
{
ExpressInformation n;//将要创建的新订单
ArrayList<ExpressInformation> data;//引用读取的数据
if(this.urgent.isSelected())//判断是否为加急件
{
n = new ExpressInformation(id_t.getText(),1,sender_t.getText(),addressee_t.getText(),
"","");//因为MySQL中的表所有列都设置为了NOT NULL,所以置入空句
}
else
{
n = new ExpressInformation(id_t.getText(),2,sender_t.getText(),addressee_t.getText(),
"","");
}
//通过SQL语句将新订单存储到数据库中
SqlOperation sql = new SqlOperation();
sql.Insert(n);
}
/*public static void main(String[] args)
{
CreatNewOrder CreatUI = new CreatNewOrder();
}*/
}
5.订单查询界面
package System;
import javax.swing.*;
import javax.swing.table.TableColumn;
import Information.ExpressInformation;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import DataBaseOperation.*;
public class QueryData extends JFrame implements ActionListener
{
JButton exit;//返回按钮暂
JTable table;//放置数据的表格组件
JScrollPane panel;//放置表格的视图组件
JPanel jp1,jp2;//放置组件的容器
Box buttonBox;//放置按钮的盒容器组件
private SqlOperation sql;//通过该类执行SQL语句对底层数据库执行更新查询数据操作
private ArrayList<ExpressInformation> data;//存储获取的数据
public QueryData()
{
this.sql = new SqlOperation();
this.sql.Load();
this.data = this.sql.getData();
//初始化容器
this.jp1 = new JPanel();
this.jp2 = new JPanel();
//初始化按钮并添加监听事件
this.exit = new JButton("返回");
this.exit.addActionListener(this);
//创建出表单GUI
InitTable();
Box buttonBox = new Box(BoxLayout.Y_AXIS);
buttonBox.add(exit);
this.add(BorderLayout.EAST,buttonBox);
this.add(BorderLayout.NORTH, new JLabel("订单列表"));
this.setLocation(600, 200);
this.setSize(800,800);
this.setTitle("订单列表");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
}
//初始化表单用函数
public void InitTable()
{
ExpressInformation p;//暂存数据用
int index = 0;//循环用
String[] colnames = {"快递类别","单号","寄件人","收件人","到站日期","签收日期"};
int rows = this.data.size();
Object[][] obj = new Object[rows][6];
for(Iterator<ExpressInformation> it = this.data.iterator();
it.hasNext() && rows != 0;)
{
p = it.next();
if(p.getKind() == 1)
{
obj[index][0] = "加急";
}
else
{
obj[index][0] = "普通";
}
obj[index][1] = p.getID();
obj[index][2] = p.getSender();
obj[index][3] = p.getAddressee();
obj[index][4] = p.getSendDate();
obj[index][5] = p.getReceiveDate();
index++;
}
JTable table=new JTable(obj, colnames);
TableColumn column=null; //TableColumn用于表示JTable的属性
int colunms = table.getColumnCount();
for(int i=0;i<colunms;i++)
{
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(100);
}
//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scroll = new JScrollPane(table);
scroll.setSize(300,300);
this.add(BorderLayout.CENTER,scroll);
//this.add(scroll);
}
public void actionPerformed(ActionEvent e)
{
this.dispose();
MainMenu main_UI = new MainMenu();
}
/*public static void main(String[] args)
{
QueryDate test = new QueryDate();
}*/
}
6.订单状态修改界面
修改后
在数据库中的体现
package System;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import javax.swing.table.TableColumn;
import DataBaseOperation.*;
import Information.*;
/*
* 修改订单信息(需要调用QueryDate)
*/
public class ModifyOrder extends JFrame implements ActionListener
{
JPanel jp1,jp2,jp3,jp4,jp5,jp6,jp7;//摆放标签,文本框,按钮的容器
JTextField ID_t;//输入想要修改签收或者到站日期的订单号的文本框
JLabel ID_l;//标签
JButton have_send, have_rec, clear, delete ,back;//设置到站日期,设置签收日期,清空输入框,删除该订单,返回主菜单
Box right_box;//位于框架右侧的组件组
private ArrayList<ExpressInformation> data;//放置数据对象
private SqlOperation sql;//通过该类对数据库进行查询或者修改
public ModifyOrder()
{
//操作类初始化
this.sql = new SqlOperation();
//获取表中数据的集合
this.sql.Load();
this.data = this.sql.getData();
//初始化容器
this.jp1 = new JPanel();
this.jp2 = new JPanel();
this.jp3 = new JPanel();
this.jp4 = new JPanel();
this.jp5 = new JPanel();
this.jp6 = new JPanel();
this.jp7 = new JPanel();
this.ID_l = new JLabel("订单号:");
this.ID_t = new JTextField(15);
this.jp1.add(this.ID_l);
this.jp2.add(this.ID_t);
//初始化按钮
this.have_send = new JButton("快递到站");
this.have_rec = new JButton("快递签收");
this.delete = new JButton("删除该订单");
this.clear = new JButton("清空输入");
this.back = new JButton("返回主菜单");
//将所有按钮组件放入容器再最后放入jp_main中(这样做只是因为好看点
this.jp3.add(this.have_send);
this.jp4.add(this.have_rec);
this.jp5.add(this.delete);
this.jp6.add(this.clear);
this.jp7.add(this.back);
//调用创建表单的方法
InitTable();
//按钮添加监听事件
this.have_send.addActionListener(this);
this.have_rec.addActionListener(this);
this.delete.addActionListener(this);
this.clear.addActionListener(this);
this.back.addActionListener(this);
//将放按钮组件的Box容器初始化
this.right_box = new Box(BoxLayout.Y_AXIS);//竖置摆放
this.right_box.add(this.jp1);
this.right_box.add(this.jp2);
this.right_box.add(this.jp3);
this.right_box.add(this.jp4);
this.right_box.add(this.jp5);
this.right_box.add(this.jp6);
this.right_box.add(this.jp7);
//JFrame初始化
this.add(BorderLayout.EAST,this.right_box);
this.setTitle("订单修改");
this.setLocation(600, 200);
this.setSize(700,800);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
}
public void actionPerformed(ActionEvent e)
{
ExpressInformation temp = new ExpressInformation();//暂存修改订单的对象(如果不在这进行初始化,始终会报错
if(e.getActionCommand() == "快递到站")//订单被签收,修改其签收日期
{
this.sql.Updata(this.ID_t.getText(), "SendDate");//传入修改的ID和选择修改的列
this.dispose();
ModifyOrder modify_UI = new ModifyOrder();
}
else if(e.getActionCommand() == "快递签收")
{
this.sql.Updata(this.ID_t.getText(), "ReceiveDate");
this.dispose();
ModifyOrder modify_UI = new ModifyOrder();
}
else if(e.getActionCommand() == "删除该订单")
{
this.sql.Delete(this.ID_t.getText());//传入修改的ID
this.dispose();
ModifyOrder modify_UI = new ModifyOrder();
}
else if(e.getActionCommand() == "清空输入")//清空输入框
{
clear_text();
}
else if(e.getActionCommand() == "返回主菜单")//返回主菜单
{
this.dispose();//销毁当前窗口
MainMenu m = new MainMenu();//创建主菜单窗体对象
}
}
public void InitTable()//QueryDate也用了该函数
{
ExpressInformation p;//暂存数据用
int index = 0;//循环用
String[] colnames = {"快递类别","单号","寄件人","收件人","到站日期","签收日期"};
int rows = this.data.size();
Object[][] obj = new Object[rows][6];
for(Iterator<ExpressInformation> it = this.data.iterator();
it.hasNext() && rows != 0;)
{
p = it.next();
if(p.getKind() == 1)
{
obj[index][0] = "加急";
}
else
{
obj[index][0] = "普通";
}
obj[index][1] = p.getID();
obj[index][2] = p.getSender();
obj[index][3] = p.getAddressee();
obj[index][4] = p.getSendDate();
obj[index][5] = p.getReceiveDate();
index++;
}
//创建表单组件
JTable table=new JTable(obj, colnames);
TableColumn column=null; //TableColumn用于表示JTable的属性
int colunms = table.getColumnCount();
for(int i=0;i<colunms;i++)
{
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(100);
}
//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scroll = new JScrollPane(table);
scroll.setSize(300,300);
this.add(BorderLayout.CENTER,scroll);
}
public void clear_text()//虽然只有一句,但也是为了方便以后加功能
{
this.ID_t.setText("");
}
/*public static void main(String[] args)
{
ModifyOrder test = new ModifyOrder();
}*/
}