臨近期末,java實驗報告,真的是很手忙腳亂,看了那麼多篇,沒有一篇說的比較完整的,那這篇的話就整體的說一下吧,
這個是用swing開發的學生 成績 管理系統,其中與數據庫建立連接,數據庫用的是SQL server 2012,java開發環境需要用到eclipise
因爲個人知識儲備的不足,因此代碼中有部分功能不能全部實現,本篇的源碼來源於GitHub,感謝網友分享。
本題的源代碼如下
package practice_student;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Student_Mangement extends JFrame {//程序入口
private JPanel panel_1 = new JPanel();
private JButton btnConfim = new JButton("登陸");
private JButton btnSignUp = new JButton("註冊");
private JTextField userName = new JTextField(20);
private JPasswordField pass = new JPasswordField(20);
private JLabel userLaber = new JLabel("用戶名");
private JLabel passLaber = new JLabel("密碼");
JLabel text = new JLabel("歡迎使用學生成績管理系統!");
private ConnetDB conn = new ConnetDB();
private ImageIcon icon=new ImageIcon("D:/icon.jpg");
public static void main(String[] args) {
Student_Mangement enterGui=new Student_Mangement();
}
public Student_Mangement(){
super();
this.setIconImage(icon.getImage());
this.setTitle("學生成績管理系統");
this.setBounds(650, 250, 500, 400);
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
panel_1.setLayout(null);
panel_1.setBounds(0, 50, 600, 250);
text.setBounds(140, 0, 250, 50);
btnConfim.setBounds(150, 130, 70, 30);
btnSignUp.setBounds(250,130,70,30);
userLaber.setBounds(95, 50, 40, 30);
passLaber.setBounds(95, 80, 40, 30);
userName.setBounds(135, 50, 200, 30);
pass.setBounds(135, 80, 200, 30);
panel_1.add(text);
panel_1.add(userLaber);
panel_1.add(userName);
panel_1.add(passLaber);
panel_1.add(pass);
panel_1.add(btnConfim);
panel_1.add(btnSignUp);
this.add(panel_1);
setActionLintener();
}
private void setActionLintener(){
btnConfim.addActionListener(new ActionListener() {
//內部類實現主界面
class MainGUI extends JFrame{
final int COLUMN=10;
private final List<String> TITLE= Arrays.asList("姓名","學號","教師","院系","英語成績","高數成績",
"大物成績","平均分","最高分","最低分");
Vector<Vector<String>> dataModel=new Vector<>();
private JMenuBar bar=new JMenuBar();
private JMenu menu_stu =new JMenu("管理學生成績");
private JMenu menu_course =new JMenu("課程成績排名");
private JMenu menu_exUser =new JMenu("退出登陸");
private JMenuItem showAll =new JMenuItem("顯示所有學生成績");
private JMenuItem addStu =new JMenuItem("添加學生");
private JMenuItem findByName =new JMenuItem("按關鍵字查詢");
private JMenuItem showEng =new JMenuItem("按英語成績排名");
private JMenuItem showMath =new JMenuItem("按高數成績排名");
private JMenuItem showPhy =new JMenuItem("按大物成績排名");
private JMenuItem userEx =new JMenuItem("退出登錄");
private JButton btnDelete =new JButton("刪除此條");
private JButton btnChange =new JButton("修改此條");
private JTable table;
private ConnetDB conn=new ConnetDB();
public MainGUI(){
super();
this.setTitle("學生成績管理系統");
this.setBounds(650,250,800,500);
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setIconImage(icon.getImage());
//菜單欄
menu_stu.add(showAll);
menu_stu.add(addStu);
menu_stu.add(findByName);
menu_course.add(showEng);
menu_course.add(showMath);
menu_course.add(showPhy);
menu_exUser.add(userEx);
bar.add(menu_stu);
bar.add(menu_course);
bar.add(menu_exUser);
this.setJMenuBar(bar);
Vector<String> titles=new Vector<>(TITLE);
table=new JTable(dataModel,titles);
table.getTableHeader().setReorderingAllowed(false);//表頭不可拖動
for (int i = 0; i < COLUMN; i++) {
if(1==i||i==3){//這2列數據更長一些
table.getColumnModel().getColumn(i).setPreferredWidth(150);
}
}
//承載table的panel
JPanel tablePanel=new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel,BoxLayout.Y_AXIS));
this.add(tablePanel);
JScrollPane jScrollPane=new JScrollPane();
jScrollPane.setViewportView(table);
tablePanel.add(jScrollPane, BorderLayout.CENTER);
tablePanel.add(btnChange);
tablePanel.add(btnDelete);
tablePanel.updateUI();
setActionListener();
}
//監聽事件
private void setActionListener(){
btnChange.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
if (row == -1 || column == 0) return;
String val = dataModel.get(row).get(column);
String name = dataModel.get(row).get(0);
//解決表列名和table列名不一樣
String convert="";
if(TITLE.get(column).equals("學號")) {
convert = "number";
}else if (TITLE.get(column).equals("教師")) {
convert = "teacher";
}else if (TITLE.get(column).equals("院系")) {
convert = "major";
}else if (TITLE.get(column).equals("英語成績")) {
convert = "english";
}else if (TITLE.get(column).equals("高數成績")) {
convert = "math";
}else if (TITLE.get(column).equals("大物成績")) {
convert = "physic";
}
String sql = "update Student set " + convert + " = ? where Sname = '"+name+"';";
PreparedStatement ps;
try {
ps = conn.getConnect().prepareStatement(sql);
if (TITLE.get(column).equals("學號")||TITLE.get(column).equals("英語成績")||
TITLE.get(column).equals("高數成績")||
TITLE.get(column).equals("大物成績")) {
ps.setInt(1, Integer.parseInt(val));
}
else {
ps.setString(1, val);
}
ps.executeUpdate();
} catch (SQLException e1) {
e1.printStackTrace();
}
table.validate();
table.updateUI();
}
});
btnDelete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
String sname = dataModel.get(row).get(0);
String sql = "delete from Student where Sname = '" + sname + "';";
try {
if (conn.getConnect().createStatement().executeUpdate(sql) == 0) return;
dataModel.remove(row);
//更新表格
table.validate();
table.updateUI();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
showAll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dataModel.clear();
Statement stmt;
try {
stmt =conn.getConnect().createStatement();
ResultSet rs = stmt.executeQuery("select *from Student");
initTable(rs);
} catch (SQLException e1) {
e1.printStackTrace();
}
//更新表格
table.validate();
table.updateUI();
}
});
addStu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
class AddStu extends JFrame {
ConnetDB conn = new ConnetDB();
private JTextField txName=new JTextField();
private JTextField txNo=new JTextField();
private JTextField txTeacher=new JTextField();
private JTextField txCol=new JTextField();
private JTextField txEng=new JTextField();
private JTextField txMath=new JTextField();
private JTextField txPhy=new JTextField();
private JButton btnComfirm=new JButton("確認");
private JPanel panel=new JPanel();
private JLabel lbName =new JLabel("姓名");
private JLabel lbNo =new JLabel("學號");
private JLabel lbTeacher =new JLabel("教師");
private JLabel lbCol =new JLabel("院系");
private JLabel lbEng =new JLabel("英語成績");
private JLabel lbMath =new JLabel("高數成績");
private JLabel lbPhy =new JLabel("大物成績");
public AddStu(){
super();
this.setTitle("輸入學生信息");
this.setBounds(820, 330, 350, 300);
this.setVisible(true);
this.setResizable(false);
this.setIconImage(icon.getImage());
panel.setLayout(null);
txName.setBounds(70,5,200,30);
txNo.setBounds(70,35,200,30);
txTeacher.setBounds(70,65,200,30);
txCol.setBounds(70,95,200,30);
txEng.setBounds(70,125,200,30);
txMath.setBounds(70,155,200,30);
txPhy.setBounds(70,185,200,30);
btnComfirm.setBounds(130,220,70,30);
lbName.setBounds(30,5,200,30);
lbNo.setBounds(30,35,200,30);
lbTeacher.setBounds(30,65,200,30);
lbCol.setBounds(30,95,200,30);
lbEng.setBounds(20,125,200,30);
lbMath.setBounds(20,155,200,30);
lbPhy.setBounds(20,185,200,30);
panel.add(lbName);
panel.add(txName);
panel.add(lbNo);
panel.add(txNo);
panel.add(lbTeacher);
panel.add(txTeacher);
panel.add(lbCol);
panel.add(txCol);
panel.add(lbEng);
panel.add(txEng);
panel.add(lbMath);
panel.add(txMath);
panel.add(lbPhy);
panel.add(txPhy);
panel.add(btnComfirm);
this.add(panel);
btnComfirm.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String sname="";
int sNo=Integer.parseInt(txNo.getText());
String tname="";
String col="";
int eng=Integer.parseInt(txEng.getText());
int math=Integer.parseInt(txMath.getText());
int phy=Integer.parseInt(txPhy.getText());
if (!("".equals(txName.getText()))){
sname=txName.getText();
}
if (!("".equals(txTeacher.getText()))){
tname=txTeacher.getText();
} if (!("".equals(txCol.getText()))){
col=txCol.getText();
}
String sql="insert into Student(Sname,Sno," +
"Steacher,Sdept,SEnglish,SMath,SPhystis) ";
String finalSname = sname;
String finalTname = tname;
String finalCol = col;
new Thread(() -> {//新開線程添加數據
PreparedStatement ps;
try {
ps=conn.getConnect().prepareStatement(sql);
ps.setString(1, finalSname);
ps.setInt(2, sNo);
ps.setString(3, finalTname);
ps.setString(4, finalCol);
ps.setInt(5, eng);
ps.setInt(6, math);
ps.setInt(7, phy);
ps.executeUpdate();
table.validate();
table.updateUI();
} catch (SQLException e1) {
e1.printStackTrace();
}
}).start();
dispose();
}
});
}
}
AddStu addStu=new AddStu();
}
});
findByName.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
class FindByName extends JFrame{
String input ="";
JTextField txInput=new JTextField();
JPanel panel=new JPanel();
JLabel lbInput =new JLabel("輸入");
JButton btnComfirm=new JButton("確認");
public FindByName() {
super();
this.setTitle("請輸入學號或姓名或老師或院系");
this.setBounds(820, 330, 350, 200);
this.setVisible(true);
this.setResizable(false);
this.setIconImage(icon.getImage());
panel.setLayout(null);
txInput.setBounds(70, 20, 200, 30);
lbInput.setBounds(40, 20, 200, 30);
btnComfirm.setBounds(120, 60, 70, 30);
panel.add(lbInput);
panel.add(txInput);
panel.add(btnComfirm);
this.add(panel);
btnComfirm.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
input =txInput.getText();
//使用正則表達式提取輸入數字
String regEx="[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(input);
//爲解決關鍵詞查詢String與number的衝突
int forNumber;
if ("".equals(m.replaceAll("").trim())){
forNumber=999999;
}else forNumber=Integer.parseInt(m.replaceAll("").trim());
dataModel.clear();
try {
Statement stmt = conn.getConnect().createStatement();
ResultSet rs = stmt.executeQuery("select * from Student where Sname like'%"+ input
+"%'or Sno like'%"+ forNumber
+"%'or Steacher like '%"+input+"%'or Sdept like '%"+input+"%';");
initTable(rs);
} catch (SQLException e1) {
e1.printStackTrace();
}
dispose();
table.validate();
table.updateUI();
}
});
}
}
new Thread(() -> {
FindByName finder=new FindByName();
}).start();
}
});
showEng.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dataModel.clear();
try {
Statement stmt =conn.getConnect().createStatement();
ResultSet rs = stmt.executeQuery("select *from Student order by SEnglish desc");
initTable(rs);
} catch (SQLException e1) {
e1.printStackTrace();
}
//更新表格
table.validate();
table.updateUI();
}
});
showMath.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dataModel.clear();
try {
Statement stmt =conn.getConnect().createStatement();
ResultSet rs = stmt.executeQuery("select *from Student order by SMath desc");
initTable(rs);
} catch (SQLException e1) {
e1.printStackTrace();
}
//更新表格
table.validate();
table.updateUI();
}
});
showPhy.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dataModel.clear();
try {
Statement stmt = conn.getConnect().createStatement();
ResultSet rs = stmt.executeQuery("select *from Student order by SPhystis desc ");
initTable(rs);
} catch (SQLException e1) {
e1.printStackTrace();
}
//更新表格
table.validate();
table.updateUI();
}
});
userEx.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
Student_Mangement enterGui=new Student_Mangement();
}
});
}
int Max(int a,int b,int c){
if (a>=b&&a>=c)
return a;
if (b>=a&&b>=c)
return b;
if (c>=a&&c>=b)
return c;
else return 0;
}
int Min(int a,int b,int c){
if (a<=b&&a<=c)
return a;
if (b<=a&&b<=c)
return b;
if (c<=a&&c<=b)
return c;
else return 0;
}
//table賦值
private void initTable(ResultSet rs) throws SQLException {
Vector<String> record;
while (rs.next()) {
record = new Vector<String>();
for (int i = 0; i < COLUMN; i++) {
if(i<7) {
record.add(rs.getString(i + 1));
}else if (i==7){//平均成績
record.add(Integer.toString(((rs.getInt(7)+rs.getInt(5)+rs.getInt(6))/3)));
}else if (i==8){
record.add(Integer.toString(Max(rs.getInt(5),rs.getInt(6),rs.getInt(7))));
}else if (i==9){
record.add(Integer.toString(Min(rs.getInt(5),rs.getInt(6),rs.getInt(7))));
}
}
dataModel.add(record);
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
Statement statement;
ResultSet resultSet;
String username = "";
String password = "";
username = userName.getText();
password = String.valueOf(pass.getPassword()).trim();
String sql = "select Spassword from users where Suse='" + username + "';";
try {
statement = conn.getConnect().createStatement();
resultSet = statement.executeQuery(sql);
System.out.println("執行查詢");
if (resultSet.next()) {
//用戶名對應密碼相等則進入主界面
if (resultSet.getString(1).equals(password)) {
dispose();
MainGUI mainGUI = new MainGUI();
} else {
dispose();
MainGUI mainGUI = new MainGUI();
//JOptionPane.showMessageDialog(null, "用戶名或密碼錯誤",
// "提示", JOptionPane.INFORMATION_MESSAGE);
}
}else JOptionPane.showMessageDialog(null, "用戶名或密碼錯誤",
"提示", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
btnSignUp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
class Register extends JFrame {
private JTextField txName=new JTextField();
private JTextField txPass=new JTextField();
private JButton btnComfirm=new JButton("確認");
private JLabel lbInputName =new JLabel("用戶名");
private JLabel lbInputPass =new JLabel("密碼");
private JPanel panel=new JPanel();
private ConnetDB conn=new ConnetDB();
public Register(){
super();
this.setTitle("註冊");
this.setBounds(720, 320, 350, 200);
this.setVisible(true);
this.setResizable(false);
panel.setLayout(null);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
txName.setBounds(70, 20, 200, 30);
txPass.setBounds(70, 60, 200, 30);
lbInputName.setBounds(30, 20, 40, 30);
lbInputPass.setBounds(40, 60, 40, 30);
btnComfirm.setBounds(120, 100, 70, 30);
this.add(panel);
panel.add(lbInputName);
panel.add(txName);
panel.add(lbInputPass);
panel.add(txPass);
panel.add(btnComfirm);
panel.updateUI();
btnComfirm.addActionListener(new ActionListener() {
String username="";
String password="";
@Override
public void actionPerformed(ActionEvent e) {
if (!("".equals(txName.getText()))){
username=txName.getText();
}
if (!("".equals(txPass.getText()))){
password=txPass.getText();
}
String sql="insert into users values(?,?);";
PreparedStatement ps;
try {
ps = conn.getConnect().prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "註冊成功",
"提示", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException e1) {
e1.printStackTrace();
}
dispose();
}
});
}
}
new Thread(new Runnable() {//避免窗口卡死
@Override
public void run() {
Register register =new Register();
}
}).start();
}
});
}
class ConnetDB {
public Connection getConnect(){
Connection connect = null;
//登陸數據庫的用戶
String username="sa";
String password="123456";
final String URL="jdbc:sqlserver://192.168.0.104:1433;DatabaseName=Test";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connect =DriverManager.getConnection(URL,username,password);
System.out.println("連接成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connect;
}
}
}
因爲代碼是一體的,直接建立一個類就可以使用,運行截圖,讀者可自行運行程序,來獲得截圖,這裏就不放截圖了
然後這其中最重要的一步就是連接數據庫,接下來我將敘述連接SQL server2012數據庫的方法,
首先因爲之前安裝數據庫的時候都是選擇的是Windows用戶安裝,現在我們需要將其改變爲用戶登錄模式,改變方法爲
https://zhidao.baidu.com/question/756938170935896004.html
https://blog.csdn.net/weixin_30952535/article/details/95422715
當然那個登錄名sa也是可以修改成你的名字,設置好這個以後,然後關閉軟件,這回可以嘗試用用戶名和密碼登錄。
接下來
那個IP有幾個弄幾個就行,我的反正是沒有IP10,
開啓win 7的Telent服務
若提示“不能打開到主機的連接,在端口 1433: 連接失敗”,則說明1433端口沒有打開,需要重新進行以上配置
配置環境變量
右擊 我的電腦 → 屬性 → 高級系統設置(高級) → 環境變量,在系統變量中雙擊CLASSPATH變量(或選中CLASSPATH後 → 編輯),在最後面追加 “;D:\sqljdbc4 \sqljdbc4.jar” (注意最前面有個 ; )若不存在CLASSPATH,就新建CLASSPATH變量,並且將其值設爲“D:\sqljdbc4 \sqljdbc4.jar”。
爲了以防萬一則需要在每一個文件夾下都放一個jar,下載jdbc請參考這篇文章https://blog.csdn.net/weixin_42220532/article/details/82729997
裏邊還詳細的寫明瞭如何在java中連接eclipise的代碼,下載完jdbc以後,然後把jdbc放到相應的目錄下,如下圖
建好以後一定得在項目上刷新一下以確定建立成功,然後在你建立的項目上點擊屬性
導入以後,就可以寫一段代碼來連接數據庫,因爲我用的是SQL server 2012,所以在撰寫的時候用的連接方式是SQL server的格式,讀者可根據自己的數據庫(Oracle MySQL )進行連接
packagepkg;
importjava.sql.*;
publicclass Main {
publicstatic void main(String [] args)
{
StringdriverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
StringdbURL="jdbc:sqlserver://localhost:1433;DatabaseName=你的數據庫名";
String userName="填寫你的用戶名,我的是sa";
String userPwd="填寫你的密碼";
try
{
Class.forName(driverName);
ConnectiondbConn=DriverManager.getConnection(dbURL,userName,userPwd);
System.out.println("連接數據庫成功");
}
catch(Exception e)
{
e.printStackTrace();
System.out.print("連接失敗");
}
}
}
上面的url 中 localhost 說一下,如果你的SQL 在你的本地,那麼直接寫本地的即可,如果不在本地,在虛擬機裏,則需要將localhost替換爲虛擬機的IP地址 按Windows +r 然後 cmd然後ipconfig 查看對應IpV4的地址輸入即可,DatabaseName 就是你建立數據庫的名字,下邊的
一定要填寫當初用戶數據連接時的賬號密碼,以上就是一個整個的java學生成績管理系統,通過上述方式可以和數據庫建立連接
以上文章參考於下列博主
https://blog.csdn.net/weixin_42220532/article/details/82729997
https://blog.csdn.net/stewen_001/article/details/19553173
https://blog.csdn.net/stewen_001/article/details/19553173