基于Java swing+MySQL实现学生信息管理系统:主要实现JDBC对学生信息进行增删改查,应付一般课设足矣,分享给大家。
源码:
https://github.com/ZhuangM/student.git
1、 开发环境:jdk7+MySQL5+win7
代码结构:model-dao-view
2、 数据库设计——建库建表语句
CREATEDATABASEstudent;
DROPTABLEIFEXISTS`admin`;
CREATETABLE`admin`(
`id`int(11)NOTNULLAUTO_INCREMENT,
`name`varchar(20)NOTNULL,
`username`varchar(20)NOTNULL,
`password`varchar(20)NOTNULL,
PRIMARYKEY(`id`)
)ENGINE=InnoDBAUTO_INCREMENT=2DEFAULTCHARSET=utf8;
LOCKTABLES`admin`WRITE;
INSERTINTO`admin`VALUES(1,'admin','admin','admin');
UNLOCKTABLES;
DROPTABLEIFEXISTS`student`;
CREATETABLE`student`(
`id`int(11)NOTNULLAUTO_INCREMENT,
`name`varchar(20)NOTNULL,
`sno`varchar(20)NOTNULL,
`department`varchar(20)NOTNULL,
`hometown`varchar(20)NOTNULL,
`mark`varchar(20)NOTNULL,
`email`varchar(20)NOTNULL,
`tel`varchar(20)NOTNULL,
`sex`varchar(20)NOTNULL,
PRIMARYKEY(`id`)
)ENGINE=InnoDBAUTO_INCREMENT=22DEFAULTCHARSET=utf8;
LOCKTABLES`student`WRITE;
INSERTINTO`student`VALUES(18,'张三','001','信息科学技术学院','辽宁','80','zhangsan@163.com','13888888888','男'),(19,'李四','002','理学院','上海','70','lisi@sina.com','13812341234','男'),(20,'王五','003','外国语学院','北京','88','wangwu@126.com','13698765432','女');
UNLOCKTABLES;
3、model——管理员、学生
/**
* 项目名:student
* 修改历史:
*/
package com.student.model;
/**
* 模块说明:admin
*
*/
publicclassAdmin{
privateintid;
privateString name;
privateString username;
privateString password;
publicStringgetName(){
returnname;
}
publicvoidsetName(String name){
this.name = name;
}
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id = id;
}
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(String username){
this.username = username;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(String password){
this.password = password;
}
}
/**
* 项目名:student
* 修改历史:
*/
package com.student.model;
/**
* 模块说明: 学生
*
*/
publicclassStudent {
privateint id;
privateStringsno;// 学号
privateStringname;
privateStringsex;
privateStringdepartment;// 院系
privateStringhomeTown;// 籍贯
privateStringmark;// 学分
privateStringemail;
privateStringtel;// 联系方式
publicint getId() {
returnid;
}
publicvoidsetId(int id) {
this.id = id;
}
publicStringgetSno() {
returnsno;
}
publicvoidsetSno(Stringsno) {
this.sno = sno;
}
publicStringgetName() {
returnname;
}
publicvoidsetName(Stringname) {
this.name = name;
}
publicStringgetSex() {
returnsex;
}
publicvoidsetSex(Stringsex) {
this.sex = sex;
}
publicStringgetDepartment() {
returndepartment;
}
publicvoidsetDepartment(Stringdepartment) {
this.department = department;
}
publicStringgetHomeTown() {
returnhomeTown;
}
publicvoidsetHomeTown(StringhomeTown) {
this.homeTown = homeTown;
}
publicStringgetMark() {
returnmark;
}
publicvoidsetMark(Stringmark) {
this.mark = mark;
}
publicStringgetEmail() {
returnemail;
}
publicvoidsetEmail(Stringemail) {
this.email = email;
}
publicStringgetTel() {
returntel;
}
publicvoidsetTel(Stringtel) {
this.tel = tel;
}
}
4、 工具类DBUtil(对jdbc进行封装)
/**
* 项目名:student
* 修改历史:
*/
packagecom.student.util;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importcom.student.AppConstants;
/**
* 模块说明:数据库工具类
*
*/
publicclassDBUtil{
privatestaticDBUtil db;
privateConnection conn;
privatePreparedStatement ps;
privateResultSet rs;
privateDBUtil(){
}
publicstaticDBUtilgetDBUtil(){
if(db ==null) {
db =newDBUtil();
}
returndb;
}
publicintexecuteUpdate(String sql){
intresult = -1;
if(getConn() ==null) {
returnresult;
}
try{
ps = conn.prepareStatement(sql);
result = ps.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
}
returnresult;
}
publicintexecuteUpdate(String sql, Object[] obj){
intresult = -1;
if(getConn() ==null) {
returnresult;
}
try{
ps = conn.prepareStatement(sql);
for(inti =0; i < obj.length; i++) {
ps.setObject(i +1, obj[i]);
}
result = ps.executeUpdate();
close();
}catch(SQLException e) {
e.printStackTrace();
}
returnresult;
}
publicResultSetexecuteQuery(String sql){
if(getConn() ==null) {
returnnull;
}
try{
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
}catch(SQLException e) {
e.printStackTrace();
}
returnrs;
}
publicResultSetexecuteQuery(String sql, Object[] obj){
if(getConn() ==null) {
returnnull;
}
try{
ps = conn.prepareStatement(sql);
for(inti =0; i < obj.length; i++) {
ps.setObject(i +1, obj[i]);
}
rs = ps.executeQuery();
}catch(SQLException e) {
e.printStackTrace();
}
returnrs;
}
privateConnectiongetConn(){
try{
if(conn ==null|| conn.isClosed()) {
Class.forName(AppConstants.JDBC_DRIVER);
conn = DriverManager.getConnection(AppConstants.JDBC_URL, AppConstants.JDBC_USERNAME,
AppConstants.JDBC_PASSWORD);
}
}catch(ClassNotFoundException e) {
System.out.println("jdbc driver is not found.");
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}
returnconn;
}
publicvoidclose(){
try{
if(rs !=null) {
rs.close();
}
if(ps !=null) {
ps.close();
}
if(conn !=null) {
conn.close();
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}
5、dao:主要调用DBUtil操作相应的model——增删改查
BaseDAO.java
/**
* 项目名:student
* 修改历史:
*/
packagecom.student.base;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importcom.student.DAO;
importcom.student.dao.AdminDAO;
importcom.student.dao.StudentDAO;
importcom.student.util.DBUtil;
/**
* 模块说明: DAO基类
*
*/
publicabstractclassBaseDAO{
protectedfinalDBUtil db = DBUtil.getDBUtil();
protectedResultSet rs;
privatestaticBaseDAO baseDAO;
publicBaseDAO(){
init();
}
privatevoidinit(){
// buildAbilityDAO();
}
// protected abstract void buildAbilityDAO();
publicstaticsynchronizedBaseDAOgetAbilityDAO(DAO dao){
switch(dao) {
caseAdminDAO:
if(baseDAO ==null|| baseDAO.getClass() != AdminDAO.class) {
baseDAO = AdminDAO.getInstance();
}
break;
caseStudentDAO:
if(baseDAO ==null|| baseDAO.getClass() != StudentDAO.class) {
baseDAO = StudentDAO.getInstance();
}
break;
default:
break;
}
returnbaseDAO;
}
protectedvoiddestroy(){
try{
if(rs !=null) {
rs.close();
}
}catch(SQLException se) {
se.printStackTrace();
}finally{
db.close();
}
}
}
AdminDAO.java
/**
* 项目名:student
* 修改历史:
*/
package com.student.dao;
importjava.sql.SQLException;
importcom.student.base.BaseDAO;
/**
* 模块说明: 管理员增删改查
*
*/
publicclassAdminDAOextendsBaseDAO {
privatestaticAdminDAO ad =null;
publicstaticsynchronized AdminDAO getInstance() {
if(ad ==null) {
ad =newAdminDAO();
}
returnad;
}
publicbooleanqueryForLogin(Stringusername,Stringpassword) {
booleanresult =false;
if(username.length() ==0|| password.length() ==0) {
returnresult;
}
Stringsql ="select * from admin where username=? and password=?";
String[] param = { username, password };
rs = db.executeQuery(sql, param);
try{
if(rs.next()) {
result =true;
}
}catch(SQLException e) {
e.printStackTrace();
}finally{
destroy();
}
returnresult;
}
}
StudentDAO.java
/**
* 项目名:student
* 修改历史:
*/
packagecom.student.dao;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.util.ArrayList;
importjava.util.List;
importcom.student.base.BaseDAO;
importcom.student.model.Student;
/**
* 模块说明: 学生增删改查
*
*/
publicclassStudentDAOextendsBaseDAO{
privatefinalintfieldNum =9;
privatefinalintshowNum =15;
privatestaticStudentDAO sd =null;
publicstaticsynchronizedStudentDAOgetInstance(){
if(sd ==null) {
sd =newStudentDAO();
}
returnsd;
}
// update
publicbooleanupdate(Student stu){
booleanresult =false;
if(stu ==null) {
returnresult;
}
try{
// check
if(queryBySno(stu.getSno()) ==0) {
returnresult;
}
// update
String sql ="update student set sex=?,department=?,email=?,tel=?,hometown=?,mark=? where name=? and sno=?";
String[] param = { stu.getSex(), stu.getDepartment(), stu.getEmail(), stu.getTel(), stu.getHomeTown(),
stu.getMark(), stu.getName(), stu.getSno() };
introwCount = db.executeUpdate(sql, param);
if(rowCount ==1) {
result =true;
}
}catch(SQLException se) {
se.printStackTrace();
}finally{
destroy();
}
returnresult;
}
// delete
publicbooleandelete(Student stu){
booleanresult =false;
if(stu ==null) {
returnresult;
}
String sql ="delete from student where name=? and sno=?";
String[] param = { stu.getName(), stu.getSno() };
introwCount = db.executeUpdate(sql, param);
if(rowCount ==1) {
result =true;
}
destroy();
returnresult;
}
// add
publicbooleanadd(Student stu){
booleanresult =false;
if(stu ==null) {
returnresult;
}
try{
// check
if(queryBySno(stu.getSno()) ==1) {
returnresult;
}
// insert
String sql ="insert into student(name,sno,sex,department,hometown,mark,email,tel) values(?,?,?,?,?,?,?,?)";
String[] param = { stu.getName(), stu.getSno(), stu.getSex(), stu.getDepartment(), stu.getHomeTown(),
stu.getMark(), stu.getEmail(), stu.getTel() };
if(db.executeUpdate(sql, param) ==1) {
result =true;
}
}catch(SQLException se) {
se.printStackTrace();
}finally{
destroy();
}
returnresult;
}
// query by name
publicString[][] queryByName(String name) {
String[][] result =null;
if(name.length() <0) {
returnresult;
}
List stus =newArrayList();
inti =0;
String sql ="select * from student where name like ?";
String[] param = {"%"+ name +"%"};
rs = db.executeQuery(sql, param);
try{
while(rs.next()) {
buildList(rs, stus, i);
i++;
}
if(stus.size() >0) {
result =newString[stus.size()][fieldNum];
for(intj =0; j < stus.size(); j++) {
buildResult(result, stus, j);
}
}
}catch(SQLException se) {
se.printStackTrace();
}finally{
destroy();
}
returnresult;
}
// query
publicString[][] list(intpageNum) {
String[][] result =null;
if(pageNum <1) {
returnresult;
}
List stus =newArrayList();
inti =0;
intbeginNum = (pageNum -1) * showNum;
String sql ="select * from student limit ?,?";
Integer[] param = { beginNum, showNum };
rs = db.executeQuery(sql, param);
try{
while(rs.next()) {
buildList(rs, stus, i);
i++;
}
if(stus.size() >0) {
result =newString[stus.size()][fieldNum];
for(intj =0; j < stus.size(); j++) {
buildResult(result, stus, j);
}
}
}catch(SQLException se) {
se.printStackTrace();
}finally{
destroy();
}
returnresult;
}
// 将rs记录添加到list中
privatevoidbuildList(ResultSet rs, List list,inti)throwsSQLException{
Student stu =newStudent();
stu.setId(i +1);
stu.setName(rs.getString("name"));
stu.setDepartment(rs.getString("department"));
stu.setEmail(rs.getString("email"));
stu.setHomeTown(rs.getString("hometown"));
stu.setMark(rs.getString("mark"));
stu.setSex(rs.getString("sex"));
stu.setSno(rs.getString("sno"));
stu.setTel(rs.getString("tel"));
list.add(stu);
}
// 将list中记录添加到二维数组中
privatevoidbuildResult(String[][] result, List stus,intj){
Student stu = stus.get(j);
result[j][0] = String.valueOf(stu.getId());
result[j][1] = stu.getName();
result[j][2] = stu.getSno();
result[j][3] = stu.getSex();
result[j][4] = stu.getDepartment();
result[j][5] = stu.getHomeTown();
result[j][6] = stu.getMark();
result[j][7] = stu.getEmail();
result[j][8] = stu.getTel();
}
// query by sno
privateintqueryBySno(String sno)throwsSQLException{
intresult =0;
if("".equals(sno) || sno ==null) {
returnresult;
}
String checkSql ="select * from student where sno=?";
String[] checkParam = { sno };
rs = db.executeQuery(checkSql, checkParam);
if(rs.next()) {
result =1;
}
returnresult;
}
}
6、 view:与用户交互的界面(包括LoginView.java、MainView.java、AddView.java、DeleteView.java、UpdateView.java),主要使用DAO提供的接口,由于篇幅原因,仅列出MainView即首页。
/**
* 项目名:student
* 修改历史:
*/
packagecom.student.view;
importjava.awt.BorderLayout;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.event.KeyAdapter;
importjava.awt.event.KeyEvent;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JPanel;
importjavax.swing.JScrollPane;
importjavax.swing.JTable;
importjavax.swing.JTextField;
importjavax.swing.table.DefaultTableCellRenderer;
importjavax.swing.table.DefaultTableModel;
importjavax.swing.table.TableColumn;
importcom.student.AppConstants;
importcom.student.DAO;
importcom.student.base.BaseDAO;
importcom.student.dao.StudentDAO;
/**
* 模块说明: 首页
*
*/
publicclassMainViewextendsJFrame{
privatestaticfinallongserialVersionUID =5870864087464173884L;
privatefinalintmaxPageNum =99;
privateJPanel jPanelNorth, jPanelSouth, jPanelCenter;
privateJButton jButtonFirst, jButtonLast, jButtonNext, jButtonPre, jButtonAdd, jButtonDelete, jButtonUpdate,
jButtonFind;
privateJLabel currPageNumJLabel;
privateJTextField condition;
publicstaticJTable jTable;
privateJScrollPane jScrollPane;
privateDefaultTableModel myTableModel;
publicstaticString[] column = {"id", AppConstants.STUDENT_NAME, AppConstants.STUDENT_SNO,
AppConstants.STUDENT_SEX, AppConstants.STUDENT_DEPARTMETN, AppConstants.STUDENT_HOMETOWN,
AppConstants.STUDENT_MARK, AppConstants.STUDENT_EMAIL, AppConstants.STUDENT_TEL };
publicstaticintcurrPageNum =1;
publicMainView(){
init();
}
privatevoidinit(){
setTitle(AppConstants.MAINVIEW_TITLE);
// north panel
jPanelNorth =newJPanel();
jPanelNorth.setLayout(newGridLayout(1,5));
condition =newJTextField(AppConstants.PARAM_FIND_CONDITION);
condition.addKeyListener(newFindListener());
jPanelNorth.add(condition);
// query by name
jButtonFind =newJButton(AppConstants.PARAM_FIND);
jButtonFind.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEvent e){
find();
}
});
jButtonFind.addKeyListener(newFindListener());
// add
jPanelNorth.add(jButtonFind);
jButtonAdd =newJButton(AppConstants.PARAM_ADD);
jButtonAdd.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEvent e){
newAddView();
}
});
jPanelNorth.add(jButtonAdd);
// delete
jButtonDelete =newJButton(AppConstants.PARAM_DELETE);
jButtonDelete.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEvent e){
newDeleteView();
}
});
jPanelNorth.add(jButtonDelete);
// update
jButtonUpdate =newJButton(AppConstants.PARAM_UPDATE);
jButtonUpdate.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEvent e){
newUpdateView();
}
});
jPanelNorth.add(jButtonUpdate);
// center panel
jPanelCenter =newJPanel();
jPanelCenter.setLayout(newGridLayout(1,1));
// init jTable
String[][] result = ((StudentDAO) BaseDAO.getAbilityDAO(DAO.StudentDAO)).list(currPageNum);
myTableModel =newDefaultTableModel(result, column);
jTable =newJTable(myTableModel);
DefaultTableCellRenderer cr =newDefaultTableCellRenderer();
cr.setHorizontalAlignment(JLabel.CENTER);
jTable.setDefaultRenderer(Object.class, cr);
initJTable(jTable, result);
jScrollPane =newJScrollPane(jTable);
jPanelCenter.add(jScrollPane);
// south panel
jPanelSouth =newJPanel();
jPanelSouth.setLayout(newGridLayout(1,5));
jButtonFirst =newJButton(AppConstants.MAINVIEW_FIRST);
jButtonFirst.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEvent e){
currPageNum =1;
String[][] result = ((StudentDAO) BaseDAO.getAbilityDAO(DAO.StudentDAO)).list(currPageNum);
initJTable(jTable, result);
currPageNumJLabel.setText(AppConstants.MAINVIEW_PAGENUM_JLABEL_DI + currPageNum
+ AppConstants.MAINVIEW_PAGENUM_JLABEL_YE);
}
});
jButtonPre =newJButton(AppConstants.MAINVIEW_PRE);
jButtonPre.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEvent e){
currPageNum--;
if(currPageNum <=0) {
currPageNum =1;
}
String[][] result = ((StudentDAO) BaseDAO.getAbilityDAO(DAO.StudentDAO)).list(currPageNum);
initJTable(jTable, result);
currPageNumJLabel.setText(AppConstants.MAINVIEW_PAGENUM_JLABEL_DI + currPageNum
+ AppConstants.MAINVIEW_PAGENUM_JLABEL_YE);
}
});
jButtonNext =newJButton(AppConstants.MAINVIEW_NEXT);
jButtonNext.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEvent e){
currPageNum++;
if(currPageNum > maxPageNum) {
currPageNum = maxPageNum;
}
String[][] result = ((StudentDAO) BaseDAO.getAbilityDAO(DAO.StudentDAO)).list(currPageNum);
initJTable(jTable, result);
currPageNumJLabel.setText(AppConstants.MAINVIEW_PAGENUM_JLABEL_DI + currPageNum
+ AppConstants.MAINVIEW_PAGENUM_JLABEL_YE);
}
});
jButtonLast =newJButton(AppConstants.MAINVIEW_LAST);
jButtonLast.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEvent e){
currPageNum = maxPageNum;
String[][] result = ((StudentDAO) BaseDAO.getAbilityDAO(DAO.StudentDAO)).list(currPageNum);
initJTable(jTable, result);
currPageNumJLabel.setText(AppConstants.MAINVIEW_PAGENUM_JLABEL_DI + currPageNum
+ AppConstants.MAINVIEW_PAGENUM_JLABEL_YE);
}
});
currPageNumJLabel =newJLabel(
AppConstants.MAINVIEW_PAGENUM_JLABEL_DI + currPageNum + AppConstants.MAINVIEW_PAGENUM_JLABEL_YE);
currPageNumJLabel.setHorizontalAlignment(JLabel.CENTER);
jPanelSouth.add(jButtonFirst);
jPanelSouth.add(jButtonPre);
jPanelSouth.add(currPageNumJLabel);
jPanelSouth.add(jButtonNext);
jPanelSouth.add(jButtonLast);
this.add(jPanelNorth, BorderLayout.NORTH);
this.add(jPanelCenter, BorderLayout.CENTER);
this.add(jPanelSouth, BorderLayout.SOUTH);
setBounds(400,200,750,340);
setResizable(false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
publicstaticvoidinitJTable(JTable jTable, String[][] result){
((DefaultTableModel) jTable.getModel()).setDataVector(result, column);
jTable.setRowHeight(20);
TableColumn firsetColumn = jTable.getColumnModel().getColumn(0);
firsetColumn.setPreferredWidth(30);
firsetColumn.setMaxWidth(30);
firsetColumn.setMinWidth(30);
TableColumn secondColumn = jTable.getColumnModel().getColumn(1);
secondColumn.setPreferredWidth(60);
secondColumn.setMaxWidth(60);
secondColumn.setMinWidth(60);
TableColumn thirdColumn = jTable.getColumnModel().getColumn(2);
thirdColumn.setPreferredWidth(90);
thirdColumn.setMaxWidth(90);
thirdColumn.setMinWidth(90);
TableColumn fourthColumn = jTable.getColumnModel().getColumn(3);
fourthColumn.setPreferredWidth(30);
fourthColumn.setMaxWidth(30);
fourthColumn.setMinWidth(30);
TableColumn seventhColumn = jTable.getColumnModel().getColumn(6);
seventhColumn.setPreferredWidth(30);
seventhColumn.setMaxWidth(30);
seventhColumn.setMinWidth(30);
TableColumn ninthColumn = jTable.getColumnModel().getColumn(8);
ninthColumn.setPreferredWidth(90);
ninthColumn.setMaxWidth(90);
ninthColumn.setMinWidth(90);
}
privateclassFindListenerextendsKeyAdapter{
@Override
publicvoidkeyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
find();
}
}
}
privatevoidfind(){
currPageNum =0;
String param = condition.getText();
if("".equals(param) || param ==null) {
initJTable(MainView.jTable,null);
currPageNumJLabel.setText(AppConstants.MAINVIEW_FIND_JLABEL);
return;
}
String[][] result = ((StudentDAO) BaseDAO.getAbilityDAO(DAO.StudentDAO)).queryByName(param);
condition.setText("");
initJTable(MainView.jTable, result);
currPageNumJLabel.setText(AppConstants.MAINVIEW_FIND_JLABEL);
}
}
公众号:javafirst
网友评论