项目目标和主要内容
(1)设计一个小型信息管理系统。
项目主要功能
建立用户信息数据库,实现管理员用户的登录,并使得管理员可以对数据库数据进行增删改查。
项目总体框架
其中管理员登录系统的结构图如下:
即管理员登录需要“用户名”与“密码”。
其中学生信息的结构图如下:
即学生有“姓名”、“性别”、“学号”、“联系方式”、“出生日期”、“编号”、“政治面貌”这些信息。
- 登录用户名及登录密码
字段 | 数据类型 | 说明 |
Username | varchar | 用户名 |
Password | varchar | 登录密码 |
- 学生信息表
字段 | 数据类型 | 说明 |
id | int | 编号 |
name | varchar | 姓名 |
sex | varchar | 性别 |
telephone | varchar | 联系方式 |
number | varchar | 学号 |
birthday | varchar | 出生日期 |
note | varchar | 政治面貌 |
创建
create database stuManage;
use stumanage;
create table user
(
username char(10) null,
password char(10) null
);
create table student
(
id int auto_increment,
name char(10) null,
sex char(10) null,
telephone char(20) null,
number char(20) null,
birthday char(10) null,
note char(10) null,
constraint student_pk
primary key (id)
);
增删改查:
insert into my_address_book(name, sex, telephone, number, birthday, note)value(?,?,?,?,?,?)
delete from my_address_book where id=?
update my_address_book set name=?,sex=?,telephone=?,number=?,birthday=?,note=? where id=?
select * from my_address_book where name like'%" + key + "%'
源代码
connect类
package manage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class connect {
private static String driverName = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/manage?useUnicode=true&useCharacter=utf8&useSSL=true&serverTimezone=GMT";
private static String userName = "root";
private static String password = "123456";
private Connection conn;
private Statement stmt;
public connect() {
try {
Class.forName(driverName);//加载数据库
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, userName, password);//使用DriverManger获取数据库连接
}
public void dispose() {
try {
if (conn != null) {
conn.close();
}
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
login类
package manage;
import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
//登录界面
public class login {
public static void main(String args[]) {
login l=new login();//实例化Login对象
l.showUI();
}
public void showUI() {
JFrame login=new JFrame();//创建一个JFrame容器窗口
login.setTitle("登录系统");//设置标题
login.setSize(340,240);//设置窗口大小
login.setDefaultCloseOperation(3);//0-DO_NITHING窗口无法关闭;1-HIDE隐藏程序界面但没有关闭程序;2-DISPOSE自动隐藏释放窗体,继续运行应用程序;3-EXIT
login.setLocationRelativeTo(null);//设置窗口位置相对于指定组件的位置
login.setResizable(false);//设置窗口不可被调整大小,布尔值
//FlowLayout fl=new FlowLayout(FlowLayout.CENTER,5,5);
login.setLayout(new FlowLayout());//FloeLayout默认居中对齐,水平、垂直间距默认为5个单位
login.setVisible(true);//窗体可见
//用户名标签组件
JLabel labname=new JLabel();
labname.setText("用户名:");
labname.setPreferredSize(new Dimension(60, 60));//设置最适合窗口的位置(setPreferredSize)和JLable标签组件的宽度和高度(Dimension)
login.add(labname);//加入JFrame窗口
JTextField textname=new JTextField();//创建一个JTextField文本框用于输入用户名
textname.setPreferredSize(new Dimension(250, 30));
login.add(textname);//加入到JFrame窗口中
//密码标签组件
JLabel labpassword=new JLabel();
labpassword.setText("密 码:");
labpassword.setPreferredSize(new Dimension(60, 60));
login.add(labpassword);
JPasswordField jp=new JPasswordField();
jp.setPreferredSize(new Dimension(250, 30));
login.add(jp);
//登录按钮
JButton button=new JButton();
button.setText("登录");
button.setPreferredSize(new Dimension(100, 40));
login.add(button);
login.setVisible(true);
//为登录键添加鼠标事件监听器
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
connect dbconn = new connect();//实例化Connect对象
Statement stmt = null;
ResultSet rs = null;
try {
//用于创建一个 Statement 对象,封装 SQL 语句发送给数据库,通常用来执行不带参数的 SQL 语句
stmt = dbconn.getConnection().createStatement();
//执行查询;用statement类的executeQuery()方法来下达select指令以查询数据库,把数据库响应的查询结果存放在ResultSet类对象中供我们使用
//select * from查询在数据库中表内信息
rs = stmt.executeQuery("select * from user where username='"+textname.getText()+"' and password='"+jp.getText()+"'");
if (rs.next()) {
new studentSystem();//主界面
login.dispose();//释放登录界面窗口占用的屏幕资源
}else{
JOptionPane.showMessageDialog(null, "用户名或密码不正确!!!","提示",2);//java弹窗
}
rs.close();
} catch (SQLException e1) {
e1.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因,显示出更深的调用信息
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
}
}
MyDialog类
package manage;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class MyDialog extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;//把java对象序列化而后进行保存
private connect dbconn = new connect();
private static String id;
private JPanel pCenter, pSouth;
private JLabel nameLab, sexLab, mailLab, birthLab, phoneLab,noteLab;
private JTextField nameText, mailText, birthText, phoneText,noteText;
private JComboBox<String> sex;
private JButton yesBtn, noBtn;
public MyDialog() {}
public MyDialog(String title, Map<String, String> info) {
id = info.get("id");
if("删除联系人".equals(title)) {
deletePerson();
}else {
Font font = new Font("宋体", Font.BOLD, 14);
String[] sexType = { "-请选择-","男", "女" };//下拉列表组件添加内容
pCenter = new JPanel();
pCenter.setLayout(new GridLayout(5, 1));
nameLab = new JLabel("姓名:");
sexLab = new JLabel("性别:");
mailLab = new JLabel("学号:");
birthLab = new JLabel("生日:");
phoneLab = new JLabel("电话:");
noteLab = new JLabel("政治面貌:");
nameLab.setFont(font);
sexLab.setFont(font);
mailLab.setFont(font);
birthLab.setFont(font);
phoneLab.setFont(font);
noteLab.setFont(font);
nameText = new JTextField(10);
mailText = new JTextField(10);
birthText = new JTextField(10);
phoneText = new JTextField(10);
noteText = new JTextField(10);
sex = new JComboBox<String>(sexType);
JPanel jp1 = new JPanel();
jp1.setLayout(new FlowLayout(FlowLayout.LEFT));
jp1.add(nameLab);
jp1.add(nameText);
JPanel jp5 = new JPanel();
jp5.setLayout(new FlowLayout(FlowLayout.LEFT));
jp5.add(sexLab);
jp5.add(sex);
nameText.setText(info.get("name"));
sex.setSelectedItem(info.get("sex"));
JPanel jp2 = new JPanel();
jp2.setLayout(new FlowLayout(FlowLayout.LEFT));
jp2.add(mailLab);
jp2.add(mailText);
mailText.setText(info.get("number"));
JPanel jp3 = new JPanel();
jp3.setLayout(new FlowLayout(FlowLayout.LEFT));
jp3.add(birthLab);
jp3.add(birthText);
birthText.setText(info.get("birthday"));
JPanel jp4 = new JPanel();
jp4.setLayout(new FlowLayout(FlowLayout.LEFT));
jp4.add(phoneLab);
jp4.add(phoneText);
phoneText.setText(info.get("telephone"));
JPanel jp6 = new JPanel();
jp6.setLayout(new FlowLayout(FlowLayout.LEFT));
jp6.add(noteLab);
jp6.add(noteText);
noteText.setText(info.get("note"));
pCenter.add(jp1);
pCenter.add(jp5);
pCenter.add(jp2);
pCenter.add(jp3);
pCenter.add(jp4);
pCenter.add(jp6);
pSouth = new JPanel();
yesBtn = new JButton("以数据库保存");
yesBtn.addActionListener(this);
noBtn = new JButton("以文件保存");
noBtn.addActionListener(this);
pSouth.add(yesBtn);
pSouth.add(noBtn);
this.add(pCenter, "Center");
this.add(pSouth, "South");
this.setTitle(title);
this.setSize(400, 450);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
public void actionPerformed(ActionEvent e) {//系统功能按钮监听器
if (e.getSource() == yesBtn) {
if (this.getTitle().equals("新建学生信息")) {
dbinsertPerson();
} else if (this.getTitle().equals("修改学生信息")) {
updatePerson();
} else if (this.getTitle().equals("删除学生信息")) {
deletePerson();
}
} else if (e.getSource() == noBtn) {
fileinsertPerson();
}
}
public void insertPerson() {
if (nameText.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "请输入姓名!");//提示弹窗
return;
}
}
public void dbinsertPerson(){//将新建的学生信息写入数据库的表中
boolean flag=true;
String sql = "insert into student(name, sex, telephone, number, birthday, note)value(?,?,?,?,?,?)";
try {
//PreparedStatement 对象已预编译过,所以其执行速度要快于 Statement 对象,多次执行的 SQL 语句经常创建为 PreparedStatement 对象,以提高效率。作为 Statement 的子类,PreparedStatement 继承了 Statement 的所有功能
PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);
pstmt.setString(1, nameText.getText());
pstmt.setString(2, (String) sex.getSelectedItem());
pstmt.setString(3, phoneText.getText());
pstmt.setString(4, mailText.getText());
pstmt.setString(5, birthText.getText());
pstmt.setString(6, noteText.getText());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "新建学生信息失败!");//提示弹窗
flag = false;
} finally {
dispose();
if (flag) {
JOptionPane.showMessageDialog(null, "新建学生信息成功!");//提示弹窗
}
studentSystem.flashInfo();//将数据写入数据库
DefaultTableModel model = new DefaultTableModel(studentSystem.info, studentSystem.column);
studentSystem.infoTable.setModel(model);
TableColumn column1 = studentSystem.infoTable.getColumnModel().getColumn(0);
column1.setMaxWidth(40);
column1.setMinWidth(40);
TableColumn column3 = studentSystem.infoTable.getColumnModel().getColumn(2);
column3.setMaxWidth(40);
column3.setMinWidth(40);
}
}
public void fileinsertPerson(){//将新建的学生信息写入文件中
boolean flag=true;
try {
StringBuffer sbf=new StringBuffer();
sbf.append(nameText.getText()).append(" ")
.append((String) sex.getSelectedItem()).append(" ")
.append(phoneText.getText()).append(" ")
.append(mailText.getText()).append(" ")
.append(birthText.getText()).append(" ")
.append(noteText.getText());
File file = new File("information.txt");
FileOutputStream fos = null;
if(!file.exists()){
file.createNewFile();//如果文件不存在,就创建该文件
fos = new FileOutputStream(file);//首次写入获取
}else{
//如果文件已存在,就在文件末尾追加写入
fos = new FileOutputStream(file,true);
}
OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");//指定以UTF-8格式写入文件
osw.write(sbf.toString());
osw.write("\r\n");
osw.close();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "新建学生信息失败!");//提示弹窗
flag = false;
} finally {
dispose();
if (flag) {
JOptionPane.showMessageDialog(null, "新建学生信息成功!");//提示弹窗
}
}
}
public void deletePerson() {//删除信息
String sql = "delete from student where id=?";
try {
PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);
pstmt.setString(1, id);
pstmt.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
} finally {
dispose();
studentSystem.flashInfo();
DefaultTableModel model = new DefaultTableModel(studentSystem.info, studentSystem.column);
JOptionPane.showMessageDialog(null, "删除成功!");
studentSystem.infoTable.setModel(model);
TableColumn column1 = studentSystem.infoTable.getColumnModel().getColumn(0);
column1.setMaxWidth(40);
column1.setMinWidth(40);
TableColumn column3 = studentSystem.infoTable.getColumnModel().getColumn(2);
column3.setMaxWidth(40);
column3.setMinWidth(40);
}
}
public void updatePerson() {//修改信息
if (nameText.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "请输入姓名!");//提示弹窗
}
String sql = "update student set name=?,sex=?,telephone=?,number=?,birthday=?,note=? where id=?";
try {
PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);
pstmt.setString(1, nameText.getText());
pstmt.setString(2, (String) sex.getSelectedItem());
pstmt.setString(3, phoneText.getText());
pstmt.setString(4, mailText.getText());
pstmt.setString(5, birthText.getText());
pstmt.setString(6, noteText.getText());
pstmt.setString(7, id);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
dispose();
studentSystem.flashInfo();
DefaultTableModel model = new DefaultTableModel(studentSystem.info, studentSystem.column);
studentSystem.infoTable.setModel(model);
TableColumn column1 = studentSystem.infoTable.getColumnModel().getColumn(0);
column1.setMaxWidth(40);
column1.setMinWidth(40);
TableColumn column3 = studentSystem.infoTable.getColumnModel().getColumn(2);
column3.setMaxWidth(40);
column3.setMinWidth(40);
}
}
}
student System类
package manage;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class studentSystem extends JFrame implements ActionListener {//继承自JFrame使得这个类成为一个窗体,可以对窗体的属性进行扩展并且可以定义自己需要的特殊操作方法
private static final long serialVersionUID = 1L;//把java对象序列化而后进行保存
private Map<String, String> PersonInfo;
public static Vector<Vector<String>> info = new Vector<Vector<String>>();
private JLabel keyLab;
private JButton searchBtn, createBtn, updateBtn, deleteBtn,exitBtn;
public static JTable infoTable;
private JTextField keyText;
public static Vector<String> column;
public studentSystem() {
PersonInfo = new HashMap<String, String>();
Font font = new Font("宋体", Font.PLAIN, 15);//设置字体,类型和大小;Front.PLAIN普通,Front.BLOD加粗,Front.ITALIC斜体
JPanel pNorth = new JPanel();
pNorth.setLayout(new FlowLayout(FlowLayout.RIGHT));
keyLab = new JLabel("请输入关键字:");
keyText = new JTextField(10);//搜索文本框
//创建系统功能按钮
searchBtn = new JButton("搜索学生信息");
createBtn = new JButton("新增学生信息");
updateBtn = new JButton("修改学生信息");
deleteBtn = new JButton("删除学生信息");
exitBtn = new JButton("退出系统");
//设置字体大小
keyLab.setFont(font);
searchBtn.setFont(font);
createBtn.setFont(font);
updateBtn.setFont(font);
deleteBtn.setFont(font);
exitBtn.setFont(font);
//添加监听器
searchBtn.addActionListener(this);
createBtn.addActionListener(this);
updateBtn.addActionListener(this);
deleteBtn.addActionListener(this);
exitBtn.addActionListener(this);
//在JPanel面板的上方加入搜索功能所需的一系列组件
pNorth.add(keyLab);
pNorth.add(keyText);
pNorth.add(searchBtn);
//在JPanel面板下方加入系统功能组件
JPanel pSouth = new JPanel();
pSouth.add(createBtn);
pSouth.add(updateBtn);
pSouth.add(deleteBtn);
pSouth.add(exitBtn);
//表格数据
column = new Vector<String>();
column.add("编号");
column.add("姓名");
column.add("性别");
column.add("电话");
column.add("学号");
column.add("生日");
column.add("政治面貌");
flashInfo();//将数据存入数据库
infoTable = new JTable(info, column);
TableColumn column1 = infoTable.getColumnModel().getColumn(0);
column1.setPreferredWidth(30);//自适应
TableColumn column3 = infoTable.getColumnModel().getColumn(2);
column3.setPreferredWidth(30);//自适应
JScrollPane pCenter = new JScrollPane(infoTable);//创建垂直滚动面板
this.add(pNorth, "North");
this.add(pCenter, "Center");
this.add(pSouth, "South");
this.setTitle("学生信息管理系统");
this.setSize(800, 450);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void flashInfo() {
connect dbconn = new connect();
Statement stmt = null;
ResultSet rs = null;
info.clear();
try {
stmt = dbconn.getConnection().createStatement();//创建一个 Statement 对象,封装 SQL 语句发送给数据库
rs = stmt.executeQuery("select * from student");//下达命令执行查询语句并且存放在ResultSet对象中
while (rs.next()) {
Vector<String> row = new Vector<String>();
row.add(rs.getString(1));
row.add(rs.getString(2));
row.add(rs.getString(3));
row.add(rs.getString(4));
row.add(rs.getString(5));
row.add(rs.getString(6));
row.add(rs.getString(7));
info.add(row);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e) {
int rowNum = infoTable.getSelectedRow();//返回第一个选定行的索引
if (rowNum != -1) {
PersonInfo = new HashMap<String, String>();
//将值插入HasMap中
PersonInfo.put("id", (String) infoTable.getValueAt(rowNum, 0));//返回表格row和column位置的单元格值
PersonInfo.put("name", (String) infoTable.getValueAt(rowNum, 1));
PersonInfo.put("sex", (String) infoTable.getValueAt(rowNum, 2));
PersonInfo.put("telephone", (String) infoTable.getValueAt(rowNum, 3));
PersonInfo.put("number", (String) infoTable.getValueAt(rowNum, 4));
PersonInfo.put("birthday", (String) infoTable.getValueAt(rowNum, 5));
PersonInfo.put("note", (String) infoTable.getValueAt(rowNum, 6));
}
if (e.getSource() == searchBtn) {//搜索
String keyStr = keyText.getText();
searchInfo(keyStr);
} else if (e.getSource() == createBtn) {//新建
MyDialog InsertPane = new MyDialog("新建学生信息", new HashMap<String, String>());
InsertPane.setVisible(true);
} else if (e.getSource() == updateBtn) {//修改
if (rowNum == -1) {
JOptionPane.showMessageDialog(null, "请选择学生");//提示弹窗
}
MyDialog UpdatePane = new MyDialog("修改学生信息", PersonInfo);
UpdatePane.setVisible(true);
} else if (e.getSource() == deleteBtn) {//删除
if (rowNum == -1) {
JOptionPane.showMessageDialog(null, "请选择学生");//提示弹窗
}
MyDialog DeletePane = new MyDialog("删除学生信息", PersonInfo);
DeletePane.setVisible(true);
}else if(e.getSource()==exitBtn) {//退出
this.setVisible(false);
}
}
protected void searchInfo(String key) {//搜索
connect dbconn = new connect();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = dbconn.getConnection().createStatement();
String sql = "select * from student where name like'%" + key + "%'";
rs = stmt.executeQuery(sql);
info.clear();
while (rs.next()) {
Vector<String> row = new Vector<String>();//创建自增长数组
row.add(rs.getString(1));//向Vector中添加值
row.add(rs.getString(2));
row.add(rs.getString(3));
row.add(rs.getString(4));
row.add(rs.getString(5));
row.add(rs.getString(6));
row.add(rs.getString(7));
info.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
DefaultTableModel model = new DefaultTableModel(studentSystem.info, studentSystem.column);//构造一个 DefaultTableModel,并通过将 data 和 columnNames 传递到 setDataVector 方法来初始化该表。
studentSystem.infoTable.setModel(model);//数据绑定
TableColumn column1 = studentSystem.infoTable.getColumnModel().getColumn(0);
column1.setMaxWidth(40);
column1.setMinWidth(40);
TableColumn column3 = studentSystem.infoTable.getColumnModel().getColumn(2);
column3.setMaxWidth(40);
column3.setMinWidth(40);
}
}
public static void main(String[] args) {
new studentSystem();
}
}
界面展示