entity包:包含了两个实体类,一个学生一个用户
repository包:包含对实体类至SQL中的操作
service包:用户操作实体类的桥梁
ui包:界面包
utils包:工具包用于连接数据库和制作界面表格的工具类
lib包:引入的jar包,连接数据库的工具包
StudentInfo.java省略get、set、toString方法
package com.sgu.entity;
public class StudentInfo {
private Integer id;
private String number;
private String name;
private String address;
}
User.java省略get、set、toString方法
public class User {
private Integer id;
private String username;
private String password;
}
StudentRepository.java
package com.sgu.repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.sgu.entity.StudentInfo;
import com.sgu.utils.DBUtil;
public class StudentRepository {
/**
*
* @Title: selectUser
* @Description: 执行select查询操作
* @param sql select语句
* @param args SQL语句中的参数
* @return
* @return List
*/
public static List<StudentInfo> selectStudentInfo(String sql, Object[] args) {
List<StudentInfo> studentInfos = new ArrayList<StudentInfo>();
// 1.连接数据库
Connection connection = DBUtil.getConnection();
// 2.执行SQL命令
PreparedStatement pStatement = null;
ResultSet resultSet = null;
try {
pStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
pStatement.setObject((i + 1), args[i]);
}
resultSet = pStatement.executeQuery();
while (resultSet.next()) {
StudentInfo studentInfo = new StudentInfo();
studentInfo.setId(resultSet.getInt(1));
studentInfo.setNumber(resultSet.getString(2));
studentInfo.setName(resultSet.getString(3));
studentInfo.setAddress(resultSet.getString(4));
studentInfos.add(studentInfo);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtil.close(connection, pStatement, resultSet);
}
return studentInfos;
}
/**
*
* @Title: updateStudent
* @Description: 执行Insert update delete 语句
* @param sql Insert update delete 语句
* @param args Insert update delete 语句参数
* @return
* @return 受影响的行数
*/
public static int updateStudent(String sql, Object[] args) {
int n = 0;
Connection connection = DBUtil.getConnection();
PreparedStatement pStatement = null;
try {
pStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
pStatement.setObject((i + 1), args[i]);
}
n = pStatement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return n;
}
}
UserRepository.java
package com.sgu.repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.sgu.entity.User;
import com.sgu.utils.DBUtil;
public class UserRepository {
/**
*
* @Title: selectUser
* @Description: 执行select查询操作
* @param sql select语句
* @param args SQL语句中的参数
* @return
* @return List
*/
public static List<User> selectUser(String sql, Object[] args) {
List<User> users = new ArrayList<User>();
// 1.连接数据库
Connection connection = DBUtil.getConnection();
// 2.执行SQL命令
PreparedStatement pStatement = null;
ResultSet resultSet = null;
try {
pStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
pStatement.setObject((i + 1), args[i]);
}
resultSet = pStatement.executeQuery();
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
users.add(user);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtil.close(connection, pStatement, resultSet);
}
return users;
}
/**
*
* @Title: updateUser
* @Description: 执行Insert update delete 语句
* @param sql Insert update delete 语句
* @param args Insert update delete 语句参数
* @return
* @return 受影响的行数
*/
public static int updateUser(String sql, Object[] args) {
int n = 0;
Connection connection = DBUtil.getConnection();
PreparedStatement pStatement = null;
try {
pStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
pStatement.setObject((i + 1), args[i]);
}
n = pStatement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return n;
}
}
StudentService.java
package com.sgu.service;
import java.util.List;
import com.sgu.entity.StudentInfo;
import com.sgu.repository.StudentRepository;
public class StudentService {
/**
* 取得所有的学生信息
* @Title: getAllStudents
* @Description: TODO
* @return StudentInfo对象的List集合
* @return List
*/
public List<StudentInfo> getAllStudents() {
List<StudentInfo> stus = null;
String sql = "select * from studentinfo";
Object[] args = new Object[0];
stus = StudentRepository.selectStudentInfo(sql, args);
return stus;
}
/**
* 添加学生信息
* @Title: addStudent
* @Description: TODO
* @param stu 欲添加学生的信息
* @return 添加成功返回true,否则返回false
* @return boolean
*/
public boolean addStudent(StudentInfo stu) {
String sql = "insert into studentinfo (number,name,address) values(?,?,?)";
Object[] args = { stu.getNumber(), stu.getName(), stu.getAddress() };
if (StudentRepository.updateStudent(sql, args) > 0) {
return true;
}
return false;
}
/**
* 编辑学生信息
* @Title: editStudent
* @Description: TODO
* @param stu 编辑后的学生信息
* @return 编辑成功之后返回true,否则返回false
* @return boolean
*/
public boolean editStudent(StudentInfo stu) {
String sql = "update studentinfo set number=?,name=?,address=? where id=?";
Object[] args = { stu.getId(), stu.getNumber(), stu.getName(), stu.getAddress() };
if (StudentRepository.updateStudent(sql, args) > 0) {
return true;
}
return false;
}
/**
* 删除学生信息
* @Title: deleteStudent
* @Description: TODO
* @param id 学生id
* @return 删除成功返回true,否则返回false
* @return boolean
*/
public boolean deleteStudent(int id) {
String sql = "delete from studentinfo where id=?";
Object[] args = { id };
if (StudentRepository.updateStudent(sql, args) > 0) {
return true;
}
return false;
}
}
UserService.java
package com.sgu.service;
import java.util.List;
import com.sgu.entity.User;
import com.sgu.repository.UserRepository;
/**
* 用户业务逻辑
* @version: 1.0
* @ClassName UserService
*/
public class UserService {
/**
*
* @Title: login
* @Description: 用户登录业务逻辑
* @param username 用户名
* @param password 密码
* @return
* @return User 通过身份验证,返回User对象,否则返回null
*/
public User login(String username, String password) {
String sql = "select * from t_user where username = ? and password = ?";
Object[] args = { username, password };
List<User> users = UserRepository.selectUser(sql, args);
if (users.size() == 0) {
return null;
}
return users.get(0);
}
}
UserLogin.java
package com.sgu.ui;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import com.sgu.entity.User;
import com.sgu.service.UserService;
public class UserLogin extends JFrame implements ActionListener {
private UserService userService = new UserService();
private JLabel nameLabel = new JLabel("用户名");
private JTextField nameText = new JTextField(10);
private JLabel pwdLabel = new JLabel("密码");
private JPasswordField pwdJText = new JPasswordField(10);
private JButton btnButton = new JButton("确定");
public UserLogin() {
init();
}
private void init() {
setTitle("系统登录");
setLayout(null);
nameLabel.setBounds(40, 10, 50, 30);
nameText.setBounds(110, 10, 150, 30);
pwdLabel.setBounds(40, 50, 50, 30);
pwdJText.setBounds(110, 50, 150, 30);
btnButton.setBounds(100, 120, 80, 30);
btnButton.setActionCommand("ok");
btnButton.addActionListener(this);
add(nameLabel);
add(nameText);
add(pwdLabel);
add(pwdJText);
add(btnButton);
// 获取屏幕的宽和高
int width = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
int height = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
// 设置登录窗体位于屏幕正中央
setLocation((width - 300) / 2, (height - 200) / 2);
setSize(300, 200);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// 处理按钮单击逻辑
if (e.getActionCommand().equals("ok")) {
// 取得用户输入的用户名和密码
String username = nameText.getText();
String pwd = new String(pwdJText.getPassword());
// 调用业务逻辑判断用户身份
User user = userService.login(username, pwd);
if (user != null) {
// 关闭窗体,将用户信息传递给主窗体
MainFrame mainFrame = new MainFrame(user);
// 关闭窗体
this.dispose();
} else {
JOptionPane.showMessageDialog(this, "用户名或密码错误", "错误", JOptionPane.WARNING_MESSAGE);
}
}
}
}
StudentManagerFrame.java
package com.sgu.ui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.sgu.entity.StudentInfo;
import com.sgu.service.StudentService;
import com.sgu.utils.StuTableModel;
/**
* 学生管理子窗体,用于显示所有的学生信息和添加/删除/编辑学生
* @version: 1.0
* @ClassName StudentManagerFrame
*/
public class StudentManagerFrame extends JInternalFrame implements ActionListener {
private StudentService studentService = new StudentService();// 取得业务层对象
private JTable table;// 表格
private StuTableModel model;// 表格数据
private JLabel idLabel = new JLabel("编号");
private JLabel idText = new JLabel("0");
private JLabel numberLabel = new JLabel("学号");
private JTextField numberText = new JTextField(10);
private JLabel nameLabel = new JLabel("姓名");
private JTextField nameText = new JTextField(10);
private JLabel addressLabel = new JLabel("联系地址");
private JTextField addressText = new JTextField(10);
private JButton saveBtn = new JButton("保存");
private JButton deleteBtn = new JButton("删除");
private JButton addBtn = new JButton("添加");
public StudentManagerFrame(String title, boolean resizeable, boolean closeable, boolean max) {
super(title, resizeable, closeable, max);
init();
}
private void init() {
setLayout(new BorderLayout());// 设置子窗体的布局管理器
List<StudentInfo> stus = studentService.getAllStudents();// 取得所有学生的信息
model = new StuTableModel(stus);
table = new JTable(model);
// 表格的选择事件
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
// 当选择了某一行的时候触发事件
@Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
int row = table.getSelectedRow();// 获得选中行
StudentInfo stu = model.stus.get(row);// 获得选中的学生的信息
idText.setText(stu.getId() + "");
numberText.setText(stu.getNumber());
nameText.setText(stu.getName());
addressText.setText(stu.getAddress());
}
});
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);// 将表格添加到窗体的中间位置
// 制作学生编辑界面
JPanel panel = new JPanel();
panel.add(idLabel);
panel.add(idText);
panel.add(numberLabel);
panel.add(numberText);
panel.add(nameLabel);
panel.add(nameText);
panel.add(addressLabel);
panel.add(addressText);
saveBtn.setActionCommand("save");
saveBtn.addActionListener(this);
deleteBtn.setActionCommand("delete");
deleteBtn.addActionListener(this);
addBtn.setActionCommand("add");
addBtn.addActionListener(this);
panel.add(saveBtn);
panel.add(deleteBtn);
panel.add(addBtn);
add(panel, BorderLayout.NORTH);
setSize(800, 300);
setVisible(true);
}
// 表格的选择事件处理
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String info = "";
if (e.getActionCommand().equals("save")) {
StudentInfo stu = new StudentInfo();
stu.setId(Integer.parseInt(idText.getText()));
stu.setNumber(numberText.getText());
stu.setName(nameText.getText());
stu.setAddress(addressText.getText());
// 调用业务逻辑实现数据的编辑
if (studentService.editStudent(stu)) {
info = "编辑学生信息成功";
model.stus = studentService.getAllStudents();// 更新表格中的数据
table.updateUI();// 更新界面,获得最新的数据
} else {
info = "编辑学生信息失败";
}
}
if (e.getActionCommand().equals("delete")) {
int id = Integer.parseInt(idText.getText());
if (studentService.deleteStudent(id)) {
info = "删除学生成功";
model.stus = studentService.getAllStudents();// 更新表格中的数据
table.updateUI();// 更新界面,获得最新的数据
} else {
info = "删除学生失败";
}
}
if (e.getActionCommand().equals("add")) {
StudentInfo stu = new StudentInfo();
stu.setNumber(numberText.getText());
stu.setName(nameText.getText());
stu.setAddress(addressText.getText());
if (studentService.addStudent(stu)) {
info = "添加学生成功";
model.stus = studentService.getAllStudents();// 更新表格中的数据
table.updateUI();// 刷新表格界面,获得最新的数据
} else {
info = "添加学生失败";
}
}
JOptionPane.showMessageDialog(this, info, "消息", JOptionPane.WARNING_MESSAGE);
}
}
MainFrame.java
package com.sgu.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import com.sgu.entity.User;
/**
* 学生管理系统主窗体
* @version: 1.0
* @ClassName MainFrame
*/
public class MainFrame extends JFrame implements ActionListener {
private User user = null;
private JDesktopPane jDesktopPane = new JDesktopPane();
// 菜单
private JMenuBar menuBar = new JMenuBar();// 菜单栏
private JMenu stuManager = new JMenu("管理");
private JMenuItem showStus = new JMenuItem("学生管理");
private JMenuItem showUsers = new JMenuItem("用户管理");
public MainFrame(User user) {
this.user = user;
init();
}
private void init() {
// 添加 菜单栏中的按钮
showStus.setActionCommand("showStus");
showStus.addActionListener(this);// 注册事件监听器
stuManager.add(showStus);// 将学生管理菜单项添加到管理菜单
menuBar.add(stuManager);// 将管理菜单添加到菜单栏
setJMenuBar(menuBar);// 在窗体上设置菜单栏
add(jDesktopPane);// 在主窗体中设置承载子窗体的容器
setTitle("学生信息管理程序");
setSize(1024, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// 在菜单按钮的单击事件中,打开子窗体
StudentManagerFrame studentManagerFrame = new StudentManagerFrame("学生管理", true, true, true);
jDesktopPane.add(studentManagerFrame);
}
}
Demo.java
测试类,测试许多功能使用的类
package com.sgu.ui;
//测试数据库
public class Demo {
public static void main(String[] args) {
// ==================================================
// ==================================================
// ===================LOGIN==========================
// ==================================================
// ==================================================
UserLogin userLogin = new UserLogin();
// ==================================================
// ==================================================
// ===================CRUD===========================
// ==================================================
// ==================================================
// StudentService service = new StudentService();
// // 删除用户
// if (service.deleteStudent(4)) {
// System.out.println("删除成功");
// } else {
// System.out.println("删除失败");
// }
// 编辑用户数据
// StudentInfo studentInfo = new StudentInfo();
// studentInfo.setId(4);
// studentInfo.setNumber("20171812010");
// studentInfo.setName("我是谁");
// studentInfo.setAddress("我在那");
//
// if (service.editStudent(studentInfo)) {
// System.out.println("编辑成功");
// } else {
// System.out.println("编辑失败");
// }
// 添加用户 数据
// StudentInfo student = new StudentInfo();
// student.setNumber("20171812010");
// student.setName("不知道");
// student.setAddress("不知道");
//
// if (service.addStudent(student)) {
//
// System.out.println("添加成功");
// } else {
// System.out.println("添加失败");
// }
// 测试查询用户数据
// List stusInfos = service.getAllStudents();
// for (StudentInfo s : stusInfos) {
System.out.println(s.getId() + "\t" + s.getNumber() + "\t" + s.getName() + "\t" + s.getAddress());
// System.out.println(s.getId() + "\t" + s.getName() + "\t" + s.getAddress() + "\t" + s.getNumber() + "\t");
//
// }
// 测试登录
// UserService userService = new UserService();
// Scanner scanner = new Scanner(System.in);
// System.out.println("请输入用户名");
// String name = scanner.next();
// System.out.println("请输入密码");
// String pwd = scanner.next();
// if (userService.login(name, pwd) != null) {
// System.out.println("登录成功");
//
// } else {
// System.out.println("登录失败");
// }
}
}
DBUtil.java
package com.sgu.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil {
private static Connection connection = null;
private static final String URL = "jdbc:mysql://localhost:3306/db_student?useSSL=false";
private static final String UNAME = "root";
private static final String PWD = "root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
// TODO: handle exception
System.out.println("加载驱动失败!");
}
}
/**
*
* @Title: getConnection
* @Description: 连接数据库
* @return Connection
*/
public static Connection getConnection() {
try {
connection = DriverManager.getConnection(URL, UNAME, PWD);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("数据库连接失败!");
}
return connection;
}
/**
*
* @Title: close
* @Description: 关闭数据库连接
* @param connection Connection 对象
* @param pStatement PreparedStatement 对象
* @param rSet ResultSet 对象
* @return void
*/
public static void close(Connection connection, java.sql.PreparedStatement pStatement, ResultSet rSet) {
if (rSet != null) {
try {
rSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (pStatement != null) {
try {
pStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
StuTableModel.java
package com.sgu.utils;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import com.sgu.entity.StudentInfo;
/**
* 设置学生表格布局
* @version: 1.0
* @ClassName StuTableModel
*/
public class StuTableModel extends AbstractTableModel {
public List<StudentInfo> stus = null;// 表格中的数据
String[] columnNames = { "编号", "学号", "姓名", "联系地址" };// 列标题
public StuTableModel(List<StudentInfo> stus) {
this.stus = stus;
}
// 获得表格的行数
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return stus.size();
}
// 获得表格的列数
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return columnNames.length;
}
// 获得列名称
@Override
public String getColumnName(int column) {
// TODO Auto-generated method stub
return columnNames[column];
}
// 设置单元格是否可以修改
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
return false;
}
// 获得表格中每一个单元格的数据
@Override
public Object getValueAt(int row, int col) {
// TODO Auto-generated method stub
Object data = null;
switch (col) {
case 0:
data = stus.get(row).getId();
break;
case 1:
data = stus.get(row).getNumber();
break;
case 2:
data = stus.get(row).getName();
break;
case 3:
data = stus.get(row).getAddress();
break;
}
return data;
}
}
create database db_student;
use db_student;
create table t_user(
id int auto_increment,
username varchar(20) null,
password varchar(20) null,
primary key(id)
)engine=innodb default charset=utf8;
create table studentinfo(
id int auto_increment,
number varchar(11) null,
name varchar(10) null,
address varchar(50) null,
primary key(id)
)engine=innodb default charset=utf8;
insert into t_user(username,password) values('admin','admin');
insert into studentinfo(number,name,address) values('20171812001','刘备','涿郡');
insert into studentinfo(number,name,address) values('20171812002','关羽','河东');
insert into studentinfo(number,name,address) values('20171812003','张飞','涿郡');
select * from t_user;
select * from studentinfo;
一些功能没有完善,只写了一个学生管理的,像用户以及管理员等功能没有写,结构比较简单。