初學Java8:經過JDBC實現簡易人力資源管理系統

1,人力資源管理系統,實現查詢、添加、修改、刪除的功能。同時設計登陸界面,實現註冊、登陸,修改密碼的功能。經過登陸進入人力資源管理系統。java

2,能實現將輸入的數據保存到數據庫,並實現對數據的查詢,修改,刪除。mysql

3,在數據庫設計兩張表,分別是員工表t_staff(列包括id、姓名、性別、年齡),用戶表t_user(列包括id、用戶名、密碼),sql

3,異常處理,未實現數據有效性驗證。(上次已實現,此次主要練習目的是學習JDBC,故未實現)數據庫

4,MySQL數據庫,客戶端:SQLyog數據庫設計

 1 CREATE DATABASE HRMS_db DEFAULT CHARSET utf8;
 2 CREATE TABLE t_staff(
 3     id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
 4     NAME VARCHAR(5) NOT NULL,
 5     sex VARCHAR(1) NOT NULL,
 6     age INT NOT NULL    
 7 );
 8 
 9 SELECT * FROM t_staff;
10 
11 
12 CREATE TABLE t_user(
13     id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
14     NAME VARCHAR(10)  NOT NULL,
15     pswd VARCHAR(10)  NOT NULL
16 );
17 
18 SELECT * FROM t_user;

5,數據庫工具類-用於人力資源管理系統,這次是把數據存入數據庫,將對數據庫的操做定義成方法,能夠簡化以後的程序,提升效率。工具

  1 package hrms;
  2 
  3 import java.sql.*;
  4 
  5 /**
  6  * 數據庫工具類-用於人力資源管理系統,把數據存入數據庫
  7  * 
  8  * @author A_zhi 2016-9-8
  9  *
 10  */
 11 public class DBUtil {
 12     /**
 13      * 定義final變量
 14      */
 15     public static final String DRIVER = "com.mysql.jdbc.Driver";//驅動
 16     public static final String URL = "jdbc:mysql://localhost:3306/hrms_db?characterEncoding=utf-8";//地址
 17     public static final String USER = "root";//客戶端SQLyog用戶名爲「root」
 18     public static final String PASSWORD = "";//客戶端SQLyog無密碼
 19     private static Connection con = null;
 20 
 21     /**
 22      * 創建Java-MySQL間的鏈接
 23      * 
 24      * @return con
 25      * @throws Exception
 26      */
 27     public static Connection getConnection() throws Exception {
 28         Class.forName(DRIVER);//加載Java-MySQL驅動
 29         con = DriverManager.getConnection(URL, USER, PASSWORD);//創建鏈接
 30         return con;//返回鏈接
 31     }
 32 
 33     /**
 34      * 關閉 Connection
 35      * 
 36      * @throws Exception
 37      */
 38     public static void closeConnection() throws Exception {
 39         if (con != null && !con.isClosed()) {
 40             con.close();//關閉鏈接
 41             con = null;
 42         }
 43     }
 44 
 45     /**
 46      * 執行普通SQL命令
 47      * 
 48      * @return 要執行的SQL語句
 49      * @throws Exception
 50      */
 51     public static int executeUpdate(String sql) throws Exception {
 52         con = getConnection();// 鏈接數據庫
 53         Statement st = con.createStatement();// 建立SQL命令
 54         int r = st.executeUpdate(sql);// 執行SQL命令
 55         closeConnection();// 關閉
 56         return r;// 返回
 57     }
 58 
 59     /**
 60      * 執行預編譯SQL命令,可執行帶"?"參數的SQL語句(增長,刪除,修改)
 61      * 
 62      * @param sql
 63      *            要執行的SQL命令
 64      * @param obj
 65      *            未知數目和類型的變量
 66      * @return 要執行的SQL語句
 67      * @throws Exception
 68      */
 69     public static int executeUpdate(String sql, Object... obj) throws Exception {
 70         con = getConnection();
 71         PreparedStatement pst = con.prepareStatement(sql);// 預編譯SQL命令
 72         if (obj != null && obj.length > 0) {
 73             for (int i = 0; i < obj.length; i++) {
 74                 pst.setObject(i + 1, obj[i]);// 數據庫從1開始,
 75             }
 76         }
 77         int r = pst.executeUpdate();
 78         closeConnection();
 79         return r;
 80     }
 81 
 82     /**
 83      * 帳號驗證  註冊,登錄使用,輸入用戶名和密碼存在返回true,不然返回false
 84      * @param name 用戶名 pswd  密碼
 85      * @return Boolean
 86      * @throws Exception
 87      */
 88     public static boolean queryLogin(String name,String pswd) throws Exception {
 89         String sql = "select name  from t_user where name=? and pswd=?";
 90         ResultSet rs = executeQuery(sql, name,pswd);
 91         if (rs.next())
 92             return true;
 93         else
 94             return false;
 95     }
 96 
 97     /**
 98      * 執行SQL查詢命令
 99      * 
100      * @param sql
101      *            要執行的查詢SQL命令
102      * @param obj
103      *            未知數目和類型的變量
104      * @return 結果集ResultSet
105      * @throws Exception
106      */
107     public static ResultSet executeQuery(String sql, Object... obj) throws Exception {
108         con = getConnection();
109         PreparedStatement pst = con.prepareStatement(sql);// 仍是預編譯
110         if (obj != null && obj.length > 0) {
111             for (int i = 0; i < obj.length; i++) {
112                 pst.setObject(i + 1, obj[i]);
113             }
114         }
115         ResultSet rs = pst.executeQuery();
116         return rs;
117     }
118 }
119 // 對於封裝的查詢方法,不能在方法中關閉Connection,不然沒法在進行查詢
120 // 事先在方法外部定義Connection就是爲了查詢這個方法,其餘方法中Connection能夠定義在方法內
121 // 採用脫離鏈接的行集能夠實現關閉connection也能查詢,如下附其關鍵語法
122 // import javax.sql.rowset.CachedRowSet;
123 // import com.sun.rowset.CachedRowSetImpl;
124 // Connection con=DBUtil.getConnection();
125 // PreparedStatement pst=con.prepareStatement(sql);127 // ResultSet rs=pst.executeQuery();
128 // CachedRowSet crs=new CachedRowSetImpl();//建立行集
129 // crs.populate(rs);//將結果集保存到行集
130 // con.close();//關閉
131 // crs.last();//再查詢
132 // System.out.println(crs.getString("name"));

6,人力資源管理系統,把數據存入數據庫,運用封裝,此類爲系統的主界面以及操做方法,只有登陸以後才能進入。
學習

  1 package hrms;
  2 
  3 import java.util.Scanner;
  4 import java.sql.*;
  5 
  6 /**
  7  * 人力資源管理系統,把數據存入數據庫(運用封裝)
  8  * 
  9  * 此類提供主界面及其數據操做
 10  * 
 11  * @author A_zhi
 12  * 
 13  *         2016-9-8
 14  * 
 15  *         數據庫信息:
 16  * 
 17  *         CREATE DATABASE HRMS_db DEFAULT CHARSET utf8; CREATE TABLE t_staff(
 18  *         id INT PRIMARY KEY NOT NULL AUTO_INCREMENT , NAME VARCHAR(5) NOT
 19  *         NULL, sex VARCHAR(1) NOT NULL, age INT NOT NULL );SELECT * FROM
 20  *         t_staff;
 21  *
 22  */
 23 public class HrmsByJdbc {
 24     public static Scanner sc = new Scanner(System.in);
 25 
 26     /**
 27      * 主界面,來自以前的複製
 28      */
 29     public static void mainInterface() {
 30         while (true) {
 31             System.out.println("\n\n");
 32             System.out.println("**********************************************");
 33             System.out.println("*            人力資源管理系統                 *");
 34             System.out.println("**********************************************");
 35             System.out.println("*             一、查看員工信息                 *");
 36             System.out.println("*             二、添加員工信息                 *");
 37             System.out.println("*             三、修改員工信息                 *");
 38             System.out.println("*             四、刪除員工信息                 *");
 39             System.out.println("*             0、退出系統                     *");
 40             System.out.println("**********************************************");
 41             System.out.print("請選擇:");
 42             int num = sc.nextInt();
 43             if (num == 0) {
 44                 System.out.println("\n  Thanks For Your Use!");
 45                 System.exit(0);//退出系統,以前用的是break,可是它卻返回到了登陸界面,因此百度獲得這個表達式
 46             } else {
 47                 switch (num) {
 48                 case 1:
 49                     query();// 查詢
 50                     break;
 51                 case 2:
 52                     add();// 添加
 53                     break;
 54                 case 3:
 55                     update();// 修改
 56                     break;
 57                 case 4:
 58                     del();// 刪除
 59                     break;
 60                 default:
 61                     System.out.println("沒有這個選項,請從新輸入...");
 62                 }
 63             }
 64         }
 65     }
 66 
 67     // 一、查詢
 68     private static void query() {
 69         System.out.print("您要查詢所有信息仍是單個員工信息?\n  a、所有,b、單個 :");
 70         String num1 = sc.next();
 71         String sql = null;
 72         try {
 73             switch (num1) {
 74             case "a":
 75                 sql = "select * from t_staff";
 76                 ResultSet rsa = DBUtil.executeQuery(sql);//調用工具類的方法
 77                 System.out.println("編號\t姓名\t性別\t年齡");
 78                 while (rsa.next()) {
 79                     int id = rsa.getInt(1);
 80                     String name = rsa.getString(2);
 81                     String sex = rsa.getString(3);
 82                     int age = rsa.getInt(4);
 83                     System.out.println(id + "\t" + name + "\t" + sex + "\t" + age);
 84                 }
 85                 break;
 86             case "b":
 87                 System.out.print("請輸入您要查詢的員工id:");
 88                 int idnum = sc.nextInt();
 89                 sql = "select * from t_staff where id=?";
 90                 ResultSet rsb = DBUtil.executeQuery(sql, idnum);
 91                 System.out.println("編號\t姓名\t性別\t年齡");
 92                 while (rsb.next()) {
 93                     int id = rsb.getInt(1);
 94                     String name = rsb.getString(2);
 95                     String sex = rsb.getString(3);
 96                     int age = rsb.getInt(4);
 97                     System.out.println(id + "\t" + name + "\t" + sex + "\t" + age);
 98                 }
 99                 break;
100             default:
101                 System.out.println("沒有這個選項,請從新輸入...");
102                 break;
103             }
104 
105         } catch (SQLException e) {
106             System.out.println("數據庫錯誤:" + e.getMessage());
107             e.printStackTrace();
108         } catch (Exception e) {
109             System.out.println("其它錯誤" + e.getMessage());
110             e.printStackTrace();
111         } finally {
112             try {
113                 DBUtil.closeConnection();
114             } catch (Exception e) {
115                 System.out.println(e.getMessage());
116             }
117         }
118     }
119 
120     // 二、添加
121     private static void add() {
122         System.out.println("\t數據錄入");
123         System.out.print("姓名:");
124         String name = sc.next();
125         System.out.print("性別:");
126         String sex = sc.next();
127         System.out.print("年齡:");
128         int age = sc.nextInt();
129         String sql = "INSERT INTO t_staff(NAME,sex,age) VALUES(?,?,?)";
130         try {
131             DBUtil.executeUpdate(sql, name, sex, age);
132             System.out.println("添加成功");
133         } catch (Exception e) {
134             System.out.println("錯誤:" + e.getMessage());
135         } finally {
136             try {
137                 DBUtil.closeConnection();
138             } catch (Exception e) {
139                 e.printStackTrace();
140             }
141         }
142     }
143 
144     // 三、修改
145     private static void update() {
146         String s1 = "select * from t_staff where id=?";
147         String s2 = "update  t_staff set name=? where id=?";
148         String s3 = "update  t_staff set sex=?  where id=?";
149         String s4 = "update  t_staff set age=?  where id=?";
150         System.out.print("請輸入您要修改員工的id:");
151         int idnum3 = sc.nextInt();
152         try {
153             ResultSet rsb = DBUtil.executeQuery(s1, idnum3);
154             System.out.println("編號\t姓名\t性別\t年齡");
155             while (rsb.next()) {
156                 int id = rsb.getInt(1);
157                 String name = rsb.getString(2);
158                 String sex = rsb.getString(3);
159                 int age = rsb.getInt(4);
160                 System.out.println(id + "\t" + name + "\t" + sex + "\t" + age);
161             }
162             System.out.print("你是須要修改此人信息嗎? y/n: ");
163             String as = sc.next();
164             if ("y".equals(as)) {
165                 System.out.print("你要修改的是:a、姓名,b、性別,c、年齡 :");
166                 String as1 = sc.next();
167                 if ("a".equals(as1)) {
168                     System.out.print("請輸入姓名:");
169                     String inname = sc.next();
170                     DBUtil.executeUpdate(s2, inname, idnum3);
171                 } else if ("b".equals(as1)) {
172                     System.out.print("請輸入性別:");
173                     String sex = sc.next();
174                     DBUtil.executeUpdate(s3, sex, idnum3);
175                 } else if ("c".equals(as1)) {
176                     System.out.print("請輸入年齡:");
177                     int age = sc.nextInt();
178                     DBUtil.executeUpdate(s4, age, idnum3);
179                 } else {
180                     System.out.println("輸入錯誤,請從新輸入...");
181                 }
182             }
183             System.out.println("修改爲功!");
184         } catch (Exception e) {
185             e.printStackTrace();
186         } finally {
187             try {
188                 DBUtil.closeConnection();
189             } catch (Exception e) {
190                 e.printStackTrace();
191             }
192         }
193 
194     }
195 
196     // 四、刪除
197     private static void del() {
198         String s1 = "select * from t_staff where id=?";
199         String s2 = "delete from t_staff where id=?";
200         System.out.print("請輸入您要刪除員工的id:");
201         int idnum4 = sc.nextInt();
202         ResultSet rs4 = null;
203         try {
204             rs4 = DBUtil.executeQuery(s1, idnum4);
205             System.out.println("編號\t姓名\t性別\t年齡");
206             while (rs4.next()) {
207                 int id = rs4.getInt(1);
208                 String name = rs4.getString(2);
209                 String sex = rs4.getString(3);
210                 int age = rs4.getInt(4);
211                 System.out.println(id + "\t" + name + "\t" + sex + "\t" + age);
212             }
213             System.out.print("您肯定要刪除此人信息嗎? y/n:");
214             String as = sc.next();
215             if ("y".equals(as)) {
216                 DBUtil.executeUpdate(s2, idnum4);
217                 System.out.println("刪除成功!");
218             } else {
219                 System.out.println("刪除取消!");
220             }
221         } catch (Exception e) {
222             e.getMessage();
223         } finally {
224             try {
225                 DBUtil.closeConnection();
226             } catch (Exception e) {
227                 e.printStackTrace();
228             }
229         }
230     }
231 }

7,登陸類,提供帳戶註冊、登陸、修改密碼的方法spa

  1 package hrms;
  2 
  3 import java.util.Scanner;
  4 
  5 /**
  6  * 人力資源管理系統 用戶操做
  7  * 
  8  * 提供註冊,登陸,修改密碼的功能
  9  * 
 10  * 數據庫信息:
 11  * 
 12  * CREATE TABLE t_user( id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, NAME
 13  * VARCHAR(10) NOT NULL, pswd VARCHAR(10) NOT NULL );
 14  * 
 15  * @author A_zhi
 16  * 
 17  *         2016-9-9
 18  */
 19 public class Login {
 20     private static Scanner sc = new Scanner(System.in);
 21 
 22     /**
 23      * 註冊
 24      * 
 25      * @throws Exception
 26      */
 27     public static void register() throws Exception {
 28         System.out.println("\n");
 29         System.out.println("*--------------------------------------------*");
 30         System.out.println("*++++++++++歡迎登陸人力資源管理系統+++++++++++*");
 31         System.out.println("*--------------------------------------------*");
 32         String sql = "insert into t_user(name,pswd) values(?,?)";
 33         System.out.println("\n");
 34         while (true) {
 35             System.out.print("請輸入用戶名:");
 36             String inname = sc.next();
 37             System.out.print("  請設置密碼:");
 38             String inpswd = sc.next();
 39             boolean b = DBUtil.queryLogin(inname, inpswd);
 40             if (b) {
 41                 System.out.println("\n該用戶名已存在,請從新輸入...");
 42             } else {
 43                 DBUtil.executeUpdate(sql, inname, inpswd);
 44                 System.out.print("\n註冊成功!歡迎登陸!是否當即登錄?y/n :");
 45                 String as = sc.next();
 46                 if ("y".equals(as)) {
 47                     login();
 48                 }
 49                 break;
 50             }
 51         }
 52     }
 53 
 54     /**
 55      * 登陸
 56      */
 57     public static void login() throws Exception {
 58         System.out.println("\n");
 59         int count = 0;
 60         System.out.println("*--------------------------------------------*");
 61         System.out.println("*++++++++++歡迎登陸人力資源管理系統+++++++++++*");
 62         System.out.println("*--------------------------------------------*");
 63         while (true) {
 64             System.out.println();
 65             System.out.print("請輸入用戶名:");
 66             String inname = sc.next();
 67             System.out.print("  請輸入密碼:");
 68             String inpswd = sc.next();
 69             boolean b = DBUtil.queryLogin(inname, inpswd);
 70             if (b) {
 71                 System.out.println("即將進入...");
 72                 HrmsByJdbc.mainInterface();
 73             } else {
 74                 count++;
 75                 System.out.println("帳號與密碼不匹配,請從新輸入...\n");
 76             }
 77             if (count == 3) {
 78                 System.out.println("您連續三次輸入錯誤,已退出!");
 79                 break;
 80             }
 81         }
 82     }
 83 
 84     /**
 85      * 修改密碼
 86      * 
 87      * @throws Exception
 88      */
 89     public static void updatePswd() throws Exception {
 90         System.out.println();
 91         System.out.print("請登陸後修改密碼");
 92         System.out.println("\n");
 93         int count = 0;
 95         System.out.println("*--------------------------------------------*");
 96         System.out.println("*++++++++++歡迎登陸人力資源管理系統+++++++++++*");
 97         System.out.println("*--------------------------------------------*");
 98         while (true) {
 99             System.out.println();
100             System.out.print("請輸入用戶名:");
101             String inname = sc.next();
102             System.out.print("  請輸入密碼:");
103             String inpswd = sc.next();
104             boolean b = DBUtil.queryLogin(inname, inpswd);
105             if (b) {
106                 System.out.println("\n-----修改密碼------\n");
107                 System.out.print("  請輸入新的密碼:");
108                 String newpswd=sc.next();
109                 String sql="update t_user set pswd=? where name=?";
110                 DBUtil.executeUpdate(sql,newpswd,inname);
111                 System.out.println("\n修改爲功!請從新登陸...");
112                 login();
113             } else {
114                 count++;
115                 System.out.println("帳號與密碼不匹配,請從新輸入...\n");
116             }
117             if (count == 3) {
118                 System.out.println("您連續三次輸入錯誤,已退出!");
119                 break;
120             }
121         }
122     }
123 }

 

8,註冊登陸的主界面,提供主方法,是程序執行的入口設計

 1 package hrms;
 2 
 3 import java.util.Scanner;
 4 
 5 /**
 6  * 人力資源管理系統
 7  * 
 8  * 註冊登陸界面,程序執行入口
 9  * 
10  * @author A_zhi
11  *
12  *         2016-9-11
13  */
14 public class TextLogin {
15 
16     public static void main(String[] args) throws Exception {
17         Scanner sc = new Scanner(System.in);
18         while (true) {
19             System.out.println("\n");
20             System.out.println("*--------------------------------------------*");
21             System.out.println("*++++++++++歡迎登陸人力資源管理系統+++++++++++*");
22             System.out.println("*--------------------------------------------*");
23             System.out.println("*++++++++++++++++1,註冊++++++++++++++++++++++*");
24             System.out.println();
25             System.out.println("*++++++++++++++++2,登錄++++++++++++++++++++++*");
26             System.out.println();
27             System.out.println("*++++++++++++++++3,修改密碼++++++++++++++++++*");
28             System.out.println();
29             System.out.println("*++++++++++++++++0,退出++++++++++++++++++++++*");
30             System.out.print("請選擇:");
31             int num = sc.nextInt();
32             if (num == 0) {
33                 System.out.println("\n  Thanks For Your Use!");
34                 break;
35             } else {
36                 switch (num) {
37                 case 1:
38                     Login.register();
39                     break;
40                 case 2:
41                     Login.login();
42                     break;
43                 case 3:
44                     Login.updatePswd();;
45                     break;
46                 default:
47                     System.out.println("沒有這個選項,請從新輸入...");
48                 }
49             }
50         }
51         sc.close();
52     }
53 }

  至今學習Java已有一月有餘,去上課前兩天,我在家本身看看視頻,當時在DOS輸出了一個hello  world我都很高興,一個多月過去了,程序從幾行變成了上百行,這段時間很辛苦,很累,可是收穫仍是有的,雖然我不知道學了一個多月,能到如今的水平是夠了仍是不夠,可是我心安理得,我努力了。Java知識太多了,這段時間天天講的都不少,有的甚至來不及消化,就又開始了新的內容,天天早上7點起牀去學Java,下午7點回來,吃了飯再看看,仍是感受時間不夠。接下來的時間還須要更加努力。code

  那天晚上在一個Java學習羣,有個自學了幾天的朋友發了一個for循環的語句,可是是錯的,他說他看着視頻就能寫,不看視頻就出錯,就是記不住,我回應道,沒有什麼代碼是你去寫十遍記不住的,若是有那就再寫十遍。我之後也會盡可能再多寫對練的。

  加油!堅持!

                                                          A_zhi

                                                          2016-9-11

相關文章
相關標籤/搜索