Java开发学生管理系统



Java 学生管理系统

使用JDBC了链接本地MySQL 数据库,因此在没有建立好数据库的情况下没法成功运行

(数据库部分, Java界面部分, JDBC部分)

资源下载: http://download.csdn.net/detail/deathislikethewind/9832946

本文地址: http://blog.csdn.net/deathislikethewind/article/details/71122647

一 MySQL数据建立部分

create table tea(
tid char(10),
constraint pk_person primary key (tid),
tpassword varchar(10) not null,
tname nchar(10) not null,
tsex nchar(10) not null,
tbirthday char(10) not null,
tposition nvarchar(10) not null
);

create table stu(
sid char(10),
constraint pk_person primary key (sid),
spassword varchar(10) not null,
sname nchar(10) not null,
ssex nchar(10) not null,
sbirthday char(10) not null,
smajor nvarchar(10) not null
);



insert into tea(tid, tpassword, tname, tsex, tbirthday, tposition)
select '12', '12', '老师的名字', '男OR女', '2000/1/1', '叫兽';
insert into tea(tid, tpassword, tname, tsex, tbirthday, tposition)
select '123', '123', 'TEA', 'manORwoman', '2000/1/1', 'JiaoShou';

insert into stu(sid, spassword, sname, ssex, sbirthday, smajor)
select '123', '123', '学生的名字', '男OR女', '1999/1/1', '爪洼';
insert into stu(sid, spassword, sname, ssex, sbirthday, smajor)
select '1234', '1234', 'STU', 'manORwoman', '1999/1/1', 'ZhuaWa';
下边上图


二 图形界面部分

项目目录↓


1.项目开始界面为 Main.java(暂时注释很少如果有必要我会写上)


package stu;
/* *
 * Author ShenKai
 * */
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class Main extends JFrame{
	private Student scharacter;			//记录学生的信息 
	private Teacher tcharacter;			//记录老师的信息
	private boolean logsta 	= false;	//这是登陆状态
	private boolean mansta 	= true;		//这是权限单选的选中与不选中的一个属性不重要...		
	private boolean istea 	= true;		//权限按钮是否是老师,选中老师则 istea 是true
	
	private JPanel []jp = {new JPanel(), new JPanel(), new JPanel(), new JPanel()};
	//本界面↑分成4块jpanel 分别是
	//id 块 jp[0]
	//password 块 jp[1]
	//权限 块 jp[2]
	//按钮块 jp[3]
	
	private JLabel []jlab = {
			new JLabel("ID:", 			SwingConstants.RIGHT), 
			new JLabel("Password:", 	SwingConstants.RIGHT), 
			new JLabel("Authority:", 	SwingConstants.CENTER)};
	//几个标签不多说
	
	private JButton []jbt = {new JButton("Login"), new JButton("Restart"), new JButton("Sign In")};
	private JRadioButton jrb[] = {new JRadioButton("Teacher", mansta), new JRadioButton("Student", !mansta)};
	private ButtonGroup rbgroup = new ButtonGroup();
	private JTextField jtext;		//id文本框
	private JPasswordField jpass;	//password 密码框
	
	public static void main(String[] args) {
		Main start = new Main();
	}
	
	public Main(){
		
		jtext = new JTextField(15);
		jpass = new JPasswordField(15);
		
		jtext.setToolTipText("ID");
		jpass.setToolTipText("Password");
		
		rbgroup.add(jrb[0]);//把两个单选按钮加一个组里去
		rbgroup.add(jrb[1]);
		
		jpass.addActionListener(new ActionListener(){	//密码框的监听
			public void actionPerformed(ActionEvent e) {
				judge();								//judge() 函数 判断是否可以登陆以及切换界面
			}
		});
		//登陆
		jbt[0].addActionListener(new ActionListener() { //jbt 也就是 Jbutton ,jbt[0] 是最左边的Login 也就是登陆按钮
			public void actionPerformed(ActionEvent e) {
				judge();
			}
		});
		//重置
		jbt[1].addActionListener(new ActionListener() {	//jbt[1] 是重置
			public void actionPerformed(ActionEvent e) {
				jtext.setText(null);
				jpass.setText(null);
			}
		});
		//注册
		jbt[2].addActionListener(new ActionListener() {	//jbt[2] 注册
			public void actionPerformed(ActionEvent e) {
				dispose();								//dispose 函数 关闭本界面 ,程序进程不结束哦
				if(!istea){
					scharacter = StudentSignin.StudentIn();//这里用scharacter 存储了 注册界面的 信息 事实上我并没有用它 下边的tcharacter 同样
					}									//StudentSignin.StudentIn()函数 创建注册界面 并返回所有信息
				else
					tcharacter = TeacherSignin.TeacherIn();
			}
		});
		
		jrb[0].addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(jrb[0].isSelected())
					istea = true;
				System.out.println("老师");
			}
		});
		jrb[1].addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(jrb[1].isSelected())
					istea = false;
				System.out.println("学生");
			}
		});
		
		this.setLayout(new GridLayout(4, 1));				//上边说过要把界面分成4块对吧 (这里的GridLayout(4, 1)是说分成我记得是 '相同大小的?' 4行 1列)
		jp[0].setLayout(new FlowLayout(FlowLayout.RIGHT));	//给 jpanel 设置布局
		jp[1].setLayout(new FlowLayout(FlowLayout.RIGHT));
		jp[2].setLayout(new FlowLayout(FlowLayout.CENTER));
		
		jp[0].add(jlab[0]);			//第一行添加 jlab[0](是个标签) 就是左边的那个 ("ID:")
		jp[0].add(jtext);			//第一行添加jtext 就是输入id 的那个文本框
		
		jp[1].add(jlab[1]);			//第二行添加 jlab[1](是个标签) 就是左边的那个 ("password:")
		jp[1].add(jpass);			//第二行添加jtext 就是输入password 的那个文本框
		
		jp[2].add(jlab[2]);			//添加权限(是个标签) 
		jp[2].add(jrb[0]);			//添加 单选按钮 teacher
		jp[2].add(jrb[1]);			//添加单选按钮 student
		
		jp[3].add(jbt[0]);			//按钮 login 登陆
		jp[3].add(jbt[1]);			//按钮restart 重置
		jp[3].add(jbt[2]);			//按钮 signin 注册(是不是这么拼的啊 早知道查查字典了...)
		
		this.add(jp[0]);			//ok, 把4个jpanel 加到本界面里边去 ,因为本界面 extends jframe 所以 和jframe 一样用咯
		this.add(jp[1]);
		this.add(jp[2]);
		this.add(jp[3]);
		
		this.setTitle("Stytem Of Student"); 	//标题
		this.setVisible(true);					//显示与否
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭进程
		this.setLocationRelativeTo(null);		//放到屏幕中央
		this.pack();							//自适应大小
		this.setResizable(false);				//不允许修改窗口大小
	}
	
	public void judge(){
		String pass = new String(jpass.getPassword());				//先定义一份内部String存储密码
		
		if(istea){													//这里是,如果选中了老师权限
			tcharacter = ControlMysql.gettea(jtext.getText(), pass);
			//↑↑↑↑↑ 用tcharacter 存储接受的teacher 信息, ControlMysql.gettea(jtext.getText(), pass) 这个是连接了数据库然后jtext.getText()得到的是id,password是密码 
			//↑↑↑↑↑ (续上边) 验证后如果id和密码正确的话 就会得到一个teacher类型的数据, 如果验证不成功就睡返回一个全是null 的teacher类型的数据 因此下边就用了这个, 注意tcharacter.getID() 是 从数据库返回的类的 id 
			if(tcharacter.getID() != null){
				logsta = true;				//登陆成功
				showMessage(logsta);		//显示消息 logsta (登陆状态)是 true
				dispose();					//关闭本界面
				TeacherUI.TeacherInfo(tcharacter); //新的界面 .TeacherInfo(tcharacter) 此函数是导入教师信息同时切换界面
			}
			else{
				logsta = false;				//登陆失败
				showMessage(logsta);		//显示失败了的消息
			}
//			if(logsta)System.out.println("t:\nID:"+ tcharacter.getID() + "\nLogin");
//			else System.out.println("t:\nID:"+ tcharacter.getID() + "\nNot Login");
		}
		else{
			
			scharacter = ControlMysql.getstu(jtext.getText(), pass);
			if(scharacter.getID() != null){
				logsta = true;
				showMessage(logsta);
				dispose();
				StudentUI.StudentInfo(scharacter);
			}
			else{
				logsta = false;
				showMessage(logsta);
			}
			if(logsta)System.out.println("s:\nID:"+ scharacter.getID() + "\nLogin");
			else System.out.println("s:\nID:"+ scharacter.getID() + "\nNot Login");
		}
		
	}
	
	public void showMessage(boolean ok){
		if(ok) JOptionPane.showMessageDialog(null, "Success Login", "Login Tip", JOptionPane.WARNING_MESSAGE);
		  else JOptionPane.showMessageDialog(null, "Failed Login", "Login Tip", JOptionPane.ERROR_MESSAGE);
	}
	//提示消息
}



输入错误的密码和id 就会报错咯


2.1 Login - 权限 = teacher 

登陆成功就会切换到UI界面

package stu;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
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.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class TeacherUI extends JFrame implements ActionListener{
	private Student stu = new Student();
	private Student []stus;
	//	stus = new Student[] ;
	//student
	private String col[] = {"ID","Name", "Password", "Sex", "Birthday", "Major"};
	
	private DefaultTableModel model = new DefaultTableModel(col, 0);
	private JTable table = new JTable(model);
	private JScrollPane jsStu = new JScrollPane(table);
	/*
	在构建表格的时候,只有将JTable加入到JScrollPane中才会显示列名,代码如下:
        private String col[] = {"ID","Name", "Password", "Sex", "Birthday", "Major"};
        private DefaultTableModel model = new DefaultTableModel(col, 0);
        private JTable table = new JTable(model);
        private JScrollPane jsStu = new JScrollPane(table);
	*/
//	model.setrowcount 设置行数
	
	//teacherUI
	private JPanel jpn = new JPanel(new GridLayout(2, 6, 10, 1)),
			jps = new JPanel(new FlowLayout());
	
	private JLabel []jlab ={
			new JLabel("ID"),
			new JLabel("Name"),
			new JLabel("Password"),
			new JLabel("Sex"),
			new JLabel("Birthday"),
			new JLabel("Position")
	};
	
	private JButton jSearch = new JButton("Search"),
			jcheck = new JButton("Check");
	
	private JTextField jinfo = new JTextField(20);
	
	public TeacherUI(Teacher tea){
		JLabel []jlab_info ={
				new JLabel(tea.getID()),
				new JLabel(tea.getName()),
				new JLabel("********"),
				new JLabel(tea.getSex()),
				new JLabel(tea.getbirthday()),
				new JLabel(tea.getPosition())
		};
		for(int i =0; i< 6; i++)
			jpn.add(jlab[i]);
			
		for(int i =0; i< 6; i++)
			jpn.add(jlab_info[i]);
		
		jSearch.addActionListener(this);
		jcheck.addActionListener(this);
		
		jps.add(jinfo, FlowLayout.LEFT);
		jps.add(jSearch, FlowLayout.CENTER);
		jps.add(jcheck, FlowLayout.RIGHT);
		
		this.setLayout(new BorderLayout());
		this.add(jpn, BorderLayout.NORTH);
		this.add(jps, BorderLayout.CENTER);
		this.add(jsStu, BorderLayout.SOUTH);
		
		this.setTitle("Check Of Teacher");
		this.setVisible(true);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.pack();
		this.setResizable(false);
	}
	
	public static void TeacherInfo(Teacher tea){
		new TeacherUI(tea);
	}

	public void actionPerformed(ActionEvent e) {
		int r =0;
		int countr = ControlMysql.SumOfStudent();	//获得学生的数量,此处是为了防止用户输入的要查的人数大于我们数据库里的学生人数
		
		if(e.getActionCommand().equals("Search")){
			String temptext = jinfo.getText();		//temptext 是 输入的 id
			stu = ControlMysql.getOnestu(temptext); //得到该id 的 学生信息
			
			int tempInt = 1;						//这是说查询的学生数量为1
			if(tempInt > countr)					//如果要查询的人数 大于数据库中的人数  那就自动修改它为总人数
				tempInt = countr;					//也就是说如果我有10条信息但是你输入让我查100个人的信息那么我就给你10个人的信息
			model.setRowCount(1);					//表格设置行数,更新数据了没有更多的行数放不下啊
			table = new JTable(model);				//唉以前的那个不知道咋用,就用个新的啦
			if(stu.getID() != null){				//验证是否得到了学生的信息就是说密码错了就得不到信息,对了就能得到 
				for(r = 0; r < tempInt; r++){		//循环添加不用说了吧
						table.setValueAt(stu.getID(), 		r, 0); //往 r 行 0 列添加 stu.getID() 
						table.setValueAt(stu.getName(), 	r, 1);
						table.setValueAt(stu.getPassword(), r, 2);
						table.setValueAt(stu.getSex(), 		r, 3);
						table.setValueAt(stu.getbirthday(), r, 4);
						table.setValueAt(stu.getmajor(), 	r, 5);
					}
			}
			else{
				for(r = 0; r < 1; r++){								//如果没有信息 就用 "null" 填充
					table.setValueAt("null",	r, 0);
					table.setValueAt("null", 	r, 1);
					table.setValueAt("null",	r, 2);
					table.setValueAt("null",	r, 3);
					table.setValueAt("null",	r, 4);
					table.setValueAt("null", 	r, 5);
				}
			}
		}
		else if(e.getActionCommand().equals("Check")){
			String temp = jinfo.getText();
			int tempInt = Integer.valueOf(temp);
			stus = ControlMysql.getSomestus(tempInt);

			if(tempInt > countr)
				tempInt = countr;
			model.setRowCount(tempInt);
			table = new JTable(model);
			for(r = 0; r < tempInt; r++){
					table.setValueAt(stus[r].getID(), 		r, 0);
					table.setValueAt(stus[r].getName(), 	r, 1);
					table.setValueAt(stus[r].getPassword(), r, 2);
					table.setValueAt(stus[r].getSex(), 		r, 3);
					table.setValueAt(stus[r].getbirthday(), r, 4);
					table.setValueAt(stus[r].getmajor(), 	r, 5);
				}
		}

	}
}




search 是查找某一个id

check是查找前几个学生(数字过大没有用)



2.2 login-权限 = student 

登陆成功切换到UI界面

package stu;

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class StudentUI extends JFrame{

	private JPanel jpn = new JPanel(new GridLayout(2, 6, 10, 1));
	
	private JLabel []jlab ={
			new JLabel("ID"),
			new JLabel("Name"),
			new JLabel("Password"),
			new JLabel("Sex"),
			new JLabel("Birthday"),
			new JLabel("Major")
	};
	
	
	public StudentUI(Student stu){
		
		JLabel []jlab_info ={
				new JLabel(stu.getID()),
				new JLabel(stu.getName()),
				new JLabel("********"),/*stu.getPassword()*/
				new JLabel(stu.getSex()),
				new JLabel(stu.getbirthday()),
				new JLabel(stu.getmajor())
		};

		for(int i =0; i< 6; i++)
			jpn.add(jlab[i]);
			
		for(int i =0; i< 6; i++)
			jpn.add(jlab_info[i]);
		
		this.setLayout(new BorderLayout());
		this.add(jpn);
		
		
		this.setTitle("Check Of Student");
		this.setVisible(true);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.pack();
		this.setResizable(false);
	}
	
	
	public static void StudentInfo(Student stu){
		new StudentUI(stu);
	}
}


3.1 sign in - 权限 = teacher   注册界面

package stu;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class TeacherSignin extends JFrame implements ActionListener{
	private static Teacher tea;

	private JPanel jpl = new JPanel(new GridLayout(7, 1, 0, 4)),
				   jpr = new JPanel(new GridLayout(7, 1, 0, 4)),
				   jps = new JPanel();
	
	private JLabel []jlab ={
			new JLabel("ID: ", 			SwingConstants.RIGHT),
			new JLabel("Name: ", 		SwingConstants.RIGHT),
			new JLabel("Password: ", 	SwingConstants.RIGHT),
			new JLabel("Again: ", 		SwingConstants.RIGHT),
			new JLabel("Sex: ", 		SwingConstants.RIGHT),
			new JLabel("Birthday: ", 	SwingConstants.RIGHT),
			new JLabel("Poisiton: ", 	SwingConstants.RIGHT)
	};
	
	private JTextField[] jt = {
			new JTextField(15),
			new JTextField(15)
	};
	
	private JPasswordField[] jpass = {
			new JPasswordField(15),
			new	JPasswordField(15)
	};
	
	//sex
	private JRadioButton []jrb ={
			new JRadioButton("Male", true),
			new JRadioButton("Female",false)
	};
	JPanel tjp = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
	private ButtonGroup bg = new ButtonGroup();
	//power
	private JRadioButton []jrbpower ={
			new JRadioButton("Professor", true)
	};
	
	private ButtonGroup bgpower = new ButtonGroup();
	private JPanel jppower = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
	
	
	//birthday 
	private JTextField	year  = new JTextField("XXXX", 5),
						month = new JTextField("XX", 5), 
						day   = new JTextField("XX", 5);
	private JPanel birthJP = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
	
	//button
	private JButton jby = new JButton("OK"),
			jbn = new JButton("Restart");

	//action
	public void actionPerformed(ActionEvent e) {
		String passwordf = new String(jpass[0].getPassword()), 
				passwords = new String(jpass[1].getPassword());
		if(e.getActionCommand() == "OK" && passwordf.equals(passwords)){
			String tempSex;
			if(jrb[0].isSelected()) tempSex = jrb[0].getText();
			else tempSex = jrb[1].getText();
			
			tea = new Teacher(jt[0].getText(), new String(jpass[0].getPassword()),jt[1].getText(), tempSex, new String(year.getText()+"/"+month.getText()+"/"+day.getText()), getPower());
			showMessage(ControlMysql.addTeacher(tea));
			System.out.println(getPower());
		}
		else if(e.getActionCommand() == "Restart"){
			
			for(int i = 0; i< 2; i++){
				jt[i].setText(null);
				jpass[i].setText(null);
			}
			
			year.setText("XXXX");
			month.setText("XX");
			day.setText("XX");
		}
		else{
			showMessage(false);
		}
	}
	//class
	public TeacherSignin(){
		this.setLayout(new BorderLayout());
		
		for(int i =0; i< 7; i++){
			jpl.add(jlab[i]);
		}
		
		for(int i =0; i< 4; i++){
			if(i<2){
				jt[i].setToolTipText("Pelase Enter The TEXT " +jlab[i].getText() +" can't be null.");
				jpr.add(jt[i]);
			}
			else{
				jpass[i-2].setToolTipText("Pelase Enter The TEXT " +jlab[i].getText() +" can't be null.");
				jpr.add(jpass[i-2]);
			}
		}
		//sex
		bg.add(jrb[0]);
		bg.add(jrb[1]);
		
		tjp.add(jrb[0]);
		tjp.add(jrb[1]);
		jpr.add(tjp);
		
		//birthday
		birthJP.add(year);
		birthJP.add(new JLabel("/"));
		birthJP.add(month);
		birthJP.add(new JLabel("/"));
		birthJP.add(day);
		jpr.add(birthJP);
		//major
		bgpower.add(jrbpower[0]);
		jppower.add(jrbpower[0]);
		jpr.add(jppower);
		
		//button
		jby.addActionListener(this);
		jbn.addActionListener(this);
		jps.setLayout(new GridLayout(2, 1, 0, 4));
		jps.add(jby);
		jps.add(jbn);
		
		
		this.add(jpl, BorderLayout.WEST);
		this.add(jpr, BorderLayout.CENTER);
		this.add(jps, BorderLayout.SOUTH);
		this.setTitle("Login Of Teacher");
		this.setVisible(true);
//		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.pack();
		this.setResizable(false);
	}

	private String getPower(){
		String tempMajor;
		for(int i = 0; i< 1; i++){
			if(jrbpower[i].isSelected()){
				tempMajor = new String(jrbpower[i].getText());
				return tempMajor;
			}
		} 
		return "NULL";
	}
	
	public void showMessage(boolean ok){
		if(ok) JOptionPane.showMessageDialog(null, "Success Signin", "Signin Tip", JOptionPane.WARNING_MESSAGE);
		else JOptionPane.showMessageDialog(null, "Failed Signin", "Signin Tip", JOptionPane.ERROR_MESSAGE);
	}
	
	public static Teacher TeacherIn(){
		new TeacherSignin();
		return tea;
	}
	
}


3.2 sign in - 权限 = student   注册界面

package stu;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class StudentSignin extends JFrame implements ActionListener{
	private static Student stu;

	private JPanel jpl = new JPanel(new GridLayout(7, 1, 0, 4)),
				   jpr = new JPanel(new GridLayout(7, 1, 0, 4)),
				   jps = new JPanel();
	
	private JLabel []jlab ={
			new JLabel("ID: ", 			SwingConstants.RIGHT),
			new JLabel("Name: ", 		SwingConstants.RIGHT),
			new JLabel("Password: ", 	SwingConstants.RIGHT),
			new JLabel("Again: ", 		SwingConstants.RIGHT),
			new JLabel("Sex: ", 		SwingConstants.RIGHT),
			new JLabel("Birthday: ", 	SwingConstants.RIGHT),
			new JLabel("Major: ", 		SwingConstants.RIGHT)
	};
	
	private JTextField[] jt = {
			new JTextField(15),
			new JTextField(15)
	};
	
	private JPasswordField[] jpass = {
			new JPasswordField(15),
			new	JPasswordField(15)
	};
	
	//sex
	private JRadioButton []jrb ={
			new JRadioButton("Male", true),
			new JRadioButton("Female",false)
	};
	JPanel tjp = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
	private ButtonGroup bg = new ButtonGroup();
	//major
	private JRadioButton []jrbmajor ={
			new JRadioButton("Software", true)
	};
	
	private ButtonGroup bgmajor = new ButtonGroup();
	private JPanel jpmajor = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
	
	
	//birthday 
	private JTextField	year  = new JTextField("XXXX", 5),
						month = new JTextField("XX", 5), 
						day   = new JTextField("XX", 5);
	private JPanel birthJP = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
	
	//button
	private JButton jby = new JButton("OK"),
			jbn = new JButton("Restart");

	//action
	public void actionPerformed(ActionEvent e) {
		String passwordf = new String(jpass[0].getPassword()), 
				passwords = new String(jpass[1].getPassword());
		if(e.getActionCommand().equals("OK") && passwordf.equals(passwords)){
			System.out.println(getMajor());
			String tempSex;
			if(jrb[0].isSelected()) tempSex = jrb[0].getText();
			else tempSex = jrb[1].getText();
			
			stu = new Student(jt[0].getText(), new String(jpass[0].getPassword()),jt[1].getText(), tempSex, new String(year.getText()+"/"+month.getText()+"/"+day.getText()), getMajor());
			showMessage(ControlMysql.addStudent(stu));
			dispose();
			StudentUI.StudentInfo(stu);
		}
		else if(e.getActionCommand().equals("Restart")){
			
			for(int i = 0; i< 2; i++){
				jt[i].setText(null);
				jpass[i].setText(null);
			}
			
			year.setText("XXXX");
			month.setText("XX");
			day.setText("XX");
		}
		else{
			showMessage(false);
		}
	}
	//class
	public StudentSignin(){
		this.setLayout(new BorderLayout());
		
		for(int i =0; i< 7; i++){
			jpl.add(jlab[i]);
		}
		
		for(int i =0; i< 4; i++){
			if(i<2){
				jt[i].setToolTipText("Pelase Enter The TEXT " +jlab[i].getText() +" can't be null.");
				jpr.add(jt[i]);
			}
			else{
				jpass[i-2].setToolTipText("Pelase Enter The TEXT " +jlab[i].getText() +" can't be null.");
				jpr.add(jpass[i-2]);
			}
		}
		//sex
		bg.add(jrb[0]);
		bg.add(jrb[1]);
		
		tjp.add(jrb[0]);
		tjp.add(jrb[1]);
		jpr.add(tjp);
		
		//birthday
		birthJP.add(year);
		birthJP.add(new JLabel("/"));
		birthJP.add(month);
		birthJP.add(new JLabel("/"));
		birthJP.add(day);
		jpr.add(birthJP);
		//major
		bgmajor.add(jrbmajor[0]);
		jpmajor.add(jrbmajor[0]);
		jpr.add(jpmajor);
		
		//button
		jby.addActionListener(this);
		jbn.addActionListener(this);
		jps.setLayout(new GridLayout(2, 1, 0, 4));
		jps.add(jby);
		jps.add(jbn);
		
		
		this.add(jpl, BorderLayout.WEST);
		this.add(jpr, BorderLayout.CENTER);
		this.add(jps, BorderLayout.SOUTH);
		this.setTitle("Login Of Student");
		this.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.pack();
		this.setResizable(false);
	}
	
	private String getMajor(){
		String tempMajor;
		for(int i = 0; i< 1; i++){
			if(jrbmajor[i].isSelected()){
				tempMajor = new String(jrbmajor[i].getText());
				return tempMajor;
			}
		} 
		return "NULL";
	}
	
	public void showMessage(boolean ok){
		if(ok) JOptionPane.showMessageDialog(null, "Success Signin", "Signin Tip", JOptionPane.WARNING_MESSAGE);
		  else JOptionPane.showMessageDialog(null, "Failed Signin", "Signin Tip", JOptionPane.ERROR_MESSAGE);
	}
	
	public static Student StudentIn(){
		new StudentSignin();
		return stu;
	}
}











4. 人物角色类

4.1 human.java

package stu;


class Human {
	
	protected String Name;
	protected String Sex;
	protected String Birthday;

	public Human(){
	}
	
	public Human(String Name, String Sex, String Birthday) {
		this.Sex = Sex;
		this.Name = Name;
		this.Birthday = Birthday;
	}
	public void printinfo() {
		System.out.println(this.toString());
	}

	public String getName() {
		return Name;
	}

	public void setName(String name) {
		Name = name;
	}

	public String getSex() {
		return Sex;
	}

	public void setSex(String sex) {
		Sex = sex;
	}
}


4.2 person.java

package stu;


public class Person extends Human{
	protected String ID;
	protected String Password;

	public Person(){
	}
	
	public Person(String ID, String Password, String Name, String Sex, String Birthday) {
		super(Name, Sex, Birthday);
		this.ID = ID;
		this.Password = Password;
	}

	public void printinfo() {
		System.out.println(this.toString());
	}

	public String getID() {
		return ID;
	}

	public void setID(String iD) {
		ID = iD;
	}

	public String getPassword() {
		return Password;
	}

	public void setPassword(String password) {
		Password = password;
	}

	public String getbirthday(){
		return Birthday;
	}
}




4.3.1 teacher.java

package stu;

public class Teacher extends Person{
	private String db = "1";
	private String position;
	public Teacher(){
		
	}
	public Teacher(String ID, String Password, String Name, String Sex, String Birthday, String position){
		super(ID, Password, Name, Sex, Birthday);
		this.position = position;
	}
//	public Teacher(Teacher t){
//		
//	}
	public String getPosition(){
		return position;
	}
}

4.3.2 student.java

package stu;

public class Student extends Person{
	private String db = "2";
	private String major;
	public Student(){
		
	}
	public Student(String ID, String Password, String Name, String Sex, String Birthday, String major){
		super(ID, Password, Name, Sex, Birthday);
		this.major = major;
	}
//	public Student(Student s){
//		
//	}
	public String getmajor(){
		return major;
	}
}

三 JDBC部分

1. 建立sql 连接 详细的部分: http://blog.csdn.net/deathislikethewind/article/details/71036900

 新建类ConnectMysql.java

package stu;

import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.SQLException;  

public class ConnectMysql{
	private static final String url = "jdbc:mysql://127.0.0.1:3306/sql?useUnicode=true&characterEncoding=utf-8&useSSL=false"; 
	//MySQL 表示连接的数据库 是 MySQL ;  127.0.0.1表示你的MySQL的远程端地址(127.0.0.1表示的是本地地址), 3306表示是这个端口
	//后边的一大串?useUnicode=true&characterEncoding=utf-8&useSSL=false 设置数据库属性如果不添加被曝↓↓↓↓
	//WARN:Establishing SSL connection without server's identity verification is not recommended.KILL WARN ?useUnicode=true&characterEncoding=utf-8&useSSL=false ↑
	private static final String name = "com.mysql.jdbc.Driver";	
	
	public static final String user = "root";			//数据库的用户名
	public static final String password = "ABCabc123";	//数据库的用户密码
	
	public Connection connect = null;					//连接类,这就是那个链接啊
    public PreparedStatement pStatement = null; 		//准备声明
    
    
    public ConnectMysql(String SqlStatement){
    	try{
    	Class.forName(name);										//指定连接类型 
    	connect = DriverManager.getConnection(url, user, password);	//获取连接 
    	pStatement = connect.prepareStatement(SqlStatement);		//准备执行语句
    	}
    	catch (Exception e) {
    		e.printStackTrace();
		}
    }
    
    
    public void close() {  
        try {  
            this.connect.close();  						//关闭链接
            this.pStatement.close();  					//关闭准备语句
        } catch (SQLException e) {  
            e.printStackTrace();
        }  
    }  
}



2.操作sql

新建类 ControlMysql.java

package stu;

import java.sql.ResultSet;  
import java.sql.SQLException; //例外


public class ControlMysql {
	private static String SqlStatement;			//准备声明
	private static ConnectMysql database;		//建立数据库的连接
	private static ResultSet resultSet;			//用于存储结果集
	private final static String tab = "\t\t";
	private static boolean flog = false;		//flog用来标记是否有这个老师的id
	
	public static int SumOfTeacher(){					//得到老师的数量
		SqlStatement = "select count(tid) from tea;";	//查询语句不多说
		database = new ConnectMysql(SqlStatement);		//前边的写的连接类, 里边的是准备执行的语句
		
		try{
			resultSet = database.pStatement.executeQuery(); //这里的executeQuery函数是说执行的是一个查询语句, 然后呢用resultset 来存储它返回的结果集
			resultSet.next(); 								//resultset存储的貌似是从null开始的, 也就是说resultset 是一个空头指针似的只有指向下一个信息块才能正常使用
			return resultSet.getInt(1);						//得到结果集的第1列(select count(tid) from tea;这个返回的是一个int类型数字而且我们需要的是一个int类型的数据,所以用getint方法)
		}													//这里getInt(1)为什么为什么不是getInt(0) 呢 找到源码的注释是这样的:columnIndex the first column is 1, the second is 2
		catch (Exception e) {
			e.printStackTrace();
		}
		MysqlClose(1);
		return 0;
	}
	
	public static int SumOfStudent(){					//得到学生的数量
		SqlStatement = "select count(sid) from stu;";
		database = new ConnectMysql(SqlStatement);
		
		try{
			resultSet = database.pStatement.executeQuery();
			resultSet.next(); 
			return resultSet.getInt(1);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		MysqlClose(1);										//关闭连接(我自己写的)如果用到了结果集也就是说是查询操作的参数就写1,因为1 被我规定为 resultSet.close(); database.close();
		return 0;
	}
	
	
	
	public static Teacher gettea(String ID, String pass){	//得到老师的信息,返回一个教师类的数据
		SqlStatement = "select * from tea;";
		database = new ConnectMysql(SqlStatement);
		
		String id = null, password = null, name = null, sex = null, birthday = null, position = null;
		
		try{
			resultSet = database.pStatement.executeQuery();
			while(resultSet.next()){
				if(resultSet.getString(1).equals(ID)){
					
					flog = true;								//flog用来标记是否有这个老师的id
					if(resultSet.getString(2).equals(pass)){
						
						id = resultSet.getString(1);
						password = resultSet.getString(2);
						name = resultSet.getString(3);
						sex = resultSet.getString(4);
						birthday = resultSet.getString(5);
						position = resultSet.getString(6);
//						System.out.println(id + tab + password + tab + name + tab + sex + tab + birthday + tab + position);
					}
					else {
						System.out.println("Wrong Password!");
					}
				}
			}
			if(!flog) System.out.println("No This ID!");
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		MysqlClose(1);
		return new Teacher(id, password, name, sex, birthday, position);
	}
	
	
	
	
	public static Student getstu(String ID, String pass){
		SqlStatement = "select * from stu;";
		database = new ConnectMysql(SqlStatement);
		
		String id = null, password = null, name = null, sex = null, birthday = null, major = null;
		
		try{
			resultSet = database.pStatement.executeQuery();
			while(resultSet.next()){					//前边忘了写了resultSet.next() 返回的是一个Boolean类型的变量值, 如果下一个数据为空就返回false不然就是true
				if(resultSet.getString(1).equals(ID)){	//验证id
					
					flog = true;
					if(resultSet.getString(2).equals(pass)){
						
						id = resultSet.getString(1);
						password = resultSet.getString(2);
						name = resultSet.getString(3);
						sex = resultSet.getString(4);
						birthday = resultSet.getString(5);
						major = resultSet.getString(6);
//						System.out.println(id + tab + password + tab + name + tab + sex + tab + birthday + tab + major);
					}
					else {
						System.out.println("Wrong Password!");
					}
				}
			}
			if(!flog) System.out.println("No This ID!");
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		MysqlClose(1);
		return new Student(id, password, name, sex, birthday, major);
	}
	
	
	
	
	
	public static boolean addStudent(Student stu){
		String id = stu.getID(), password = stu.getPassword(), name = stu.getName(),
				sex = stu.getSex(), birthday = stu.getbirthday(), major = stu.getmajor();
		System.out.println(id);
		System.out.println(password);
		System.out.println(name);
		System.out.println(sex);
		System.out.println(birthday);
		System.out.println(major);
		SqlStatement = "insert into stu(sid, spassword, sname, ssex, sbirthday, smajor)" + 
				"select '"+ id +"','" + password + "','" + name + "','" + sex + "','" + birthday + "','" + major + "';";
		database = new ConnectMysql(SqlStatement);
		System.out.println(SqlStatement);
		try{
			database.pStatement.executeUpdate();
		}
		catch(SQLException e){
			e.printStackTrace();
			return false;
		}
		MysqlClose(2);
		return true;
	}

	
	public static boolean addTeacher(Teacher tea){
		String id = tea.getID(), password = tea.getPassword(), name = tea.getName(),
				sex = tea.getSex(), birthday = tea.getbirthday(), position = tea.getPosition();
		System.out.println(id);
		System.out.println(password);
		System.out.println(name);
		System.out.println(sex);
		System.out.println(birthday);
		System.out.println(position);
		SqlStatement = "insert into tea(tid, tpassword, tname, tsex, tbirthday, tposition)" + 
				"select '"+ id +"','" + password + "','" + name + "','" + sex + "','" + birthday + "','" + position + "';";
		database = new ConnectMysql(SqlStatement);
		System.out.println(SqlStatement);
		try{
			database.pStatement.executeUpdate();
		}
		catch(SQLException e){
			e.printStackTrace();
			return false;
		}
		MysqlClose(2);										//这里关闭连接的参数是2 , 没有用到结果集所以只有database.close();
		return true;
	}
	
	public static Student getOnestu(String ID){
		SqlStatement = "select * from stu where sid = '" + ID + "';";
		database = new ConnectMysql(SqlStatement);
		
		String id = null, password = null, name = null, sex = null, birthday = null, major = null;
		
		try{
			resultSet = database.pStatement.executeQuery();
			while(resultSet.next()){
				if(resultSet.getString(1).equals(ID)){
						flog = true;
						id = resultSet.getString(1);
						password = resultSet.getString(2);
						name = resultSet.getString(3);
						sex = resultSet.getString(4);
						birthday = resultSet.getString(5);
						major = resultSet.getString(6);
				}
			}
			if(!flog) System.out.println("No This ID!");
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		MysqlClose(1);
		return new Student(id, password, name, sex, birthday, major);
	}
	
	
	public static Student[] getSomestus(int sum){
		SqlStatement = "select * from stu;";
		database = new ConnectMysql(SqlStatement);
		int i = 0;
		String id = null, password = null, name = null, sex = null, birthday = null, major = null;
		Student []stus;
		stus= new Student[sum];
		
		try{
			resultSet = database.pStatement.executeQuery();
			while(resultSet.next() && i < sum){
						flog = true;
						id = resultSet.getString(1);
						password = resultSet.getString(2);
						name = resultSet.getString(3);
						sex = resultSet.getString(4);
						birthday = resultSet.getString(5);
						major = resultSet.getString(6);
						stus[i++] = new Student(id, password, name, sex, birthday, major);
			}
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		MysqlClose(1);
		return stus;
	}
	
	
	public static void MysqlClose(int ok){
		if(1 == ok){
				try{
				resultSet.close();
				database.close();
			}
			catch(SQLException e){
				e.printStackTrace();
			}
		}
		else if(2 == ok){
			try{
				database.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}



好了,接下来开始慢慢码注释






















猜你喜欢

转载自blog.csdn.net/DeathIsLikeTheWind/article/details/71122647