t_staff(員工表)、t_user(用戶表)。CREATE DATABASE HRMS_db DEFAULT CHARSET utf8; CREATE TABLE t_staff( id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, NAME VARCHAR(5) NOT NULL, sex VARCHAR(1) NOT NULL, age INT NOT NULL ); CREATE TABLE t_user( id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, NAME VARCHAR(10) NOT NULL, pswd VARCHAR(10) NOT NULL );
DBUtil(單例連接 + PreparedStatement 封裝)public class DBUtil {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/hrms_db?characterEncoding=utf-8";
private static final String USER = "root";
private static final String PASSWORD = "";
private static Connection con = null;
public static Connection getConnection() throws Exception {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, USER, PASSWORD);
return con;
}
public static void closeConnection() throws Exception {
if (con != null && !con.isClosed()) { con.close(); con = null; }
}
// 通用增刪改(支持參數綁定)
public static int executeUpdate(String sql, Object... params) throws Exception {
con = getConnection();
PreparedStatement ps = con.prepareStatement(sql);
if (params != null) for (int i = 0; i < params.length; i++) ps.setObject(i + 1, params[i]);
int r = ps.executeUpdate();
closeConnection();
return r;
}
// 查詢(注意:ResultSet 依賴 Connection,調用方需手動關閉)
public static ResultSet executeQuery(String sql, Object... params) throws Exception {
con = getConnection();
PreparedStatement ps = con.prepareStatement(sql);
if (params != null) for (int i = 0; i < params.length; i++) ps.setObject(i + 1, params[i]);
return ps.executeQuery();
}
// 登錄驗證
public static boolean queryLogin(String name, String pswd) throws Exception {
ResultSet rs = executeQuery("SELECT name FROM t_user WHERE name=? AND pswd=?", name, pswd);
boolean ok = rs.next();
closeConnection(); // 查詢後立即關閉
return ok;
}
}
HrmsByJdbc(控制台菜單交互)mainInterface():主循環菜單,分發查詢/新增/修改/刪除操作。query():支持全表查詢與按 ID 單條查詢,格式化輸出。add():輸入姓名/性別/年齡,參數化插入防注入。update():先查後改,確認後按字段單獨更新。del():先查確認,再執行刪除。try-catch-finally 保證連接關閉,異常堆棧打印便於排查。Loginregister():檢查用戶名唯一性,寫入 t_user。login():最多 3 次重試,成功進入 HrmsByJdbc.mainInterface()。updatePswd():預留擴展(可補充舊密碼驗證 + 更新邏輯)。TextLoginpublic class TextLogin {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
while (true) {
// 打印菜單:1註冊 2登錄 3改密 0退出
int num = sc.nextInt();
switch (num) {
case 1: Login.register(); break;
case 2: Login.login(); break;
case 3: Login.updatePswd(); break;
case 0: System.out.println("Thanks For Your Use!"); return;
default: System.out.println("無效選項");
}
}
}
}
PreparedStatement + setObject,徹底防範 SQL 注入。ResultSet 時不關閉 Connection,由調用方 finally 塊統一釋放;增刪改內部自管連接生命周期。Connection.setAutoCommit(false)),生產環境必須添加。DBUtil) / Service(HrmsByJdbc) / UI(TextLogin) 雛形清晰。「從幾行 Hello World 到百行系統,一個月的碼量積累換來的是肌肉記憶與工程直覺。代碼寫十遍還記不住,就再寫十遍。堅持,比聰明更重要。」—— 作者 A_zhi 2016.9.11