【Java】JDBC編寫六步及模擬使用者登陸案例
阿新 • • 發佈:2021-01-27
JDBC的編寫的六個步驟
1.註冊驅動
2.獲取連線
3.獲取資料庫操作物件
4.執行sql
5.處理資料集
6.釋放資源
演示案例:
模擬使用者登入案例功能的實現。程式執行的時候,提供一個輸入的入口,可以讓使用者輸入使用者名稱和密碼。
初始化使用者介面的方法
private static Map<String, String> initUI() {
Scanner s = new Scanner(System.in);
System.out.println("使用者名稱");
String loginName = s.nextLine ();
System.out.println("密碼");
String loginPwd = s.nextLine();
Map<String,String> userLogininfo = new HashMap<>();
userLogininfo.put("loginName",loginName);
userLogininfo.put("loginPwd",loginPwd);
return userLogininfo;
}
驗真使用者名稱和密碼的方法
private static boolean login(Map<String, String> userLoginInfo) {
//JDBC程式碼
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
//單獨定義變數
String loginName = userLoginInfo.get("loginName");
String loginPwd = userLoginInfo.get("loginPwd" );
//打標機
boolean loginSuccess = false;
try {
//1 註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2 獲取連線
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root",
"bj5201314...");
//3 獲取資料庫操作物件
stmt = conn.createStatement();
//4 執行sql
String sql = "select * from t_user where loginName = '"+ loginName+
"' and loginPwd = '"+loginPwd+"'";
rs =stmt.executeQuery(sql);
//5 處理結構集
if(rs.next()){
//登入成功
loginSuccess = true;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
//6 釋放資源
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return loginSuccess ;
}
主函式
public static void main(String[] args) {
//初始化一個介面
Map<String,String> userinfo = initUI();
//驗真使用者名稱和密碼
boolean loginSuccess = login(userinfo);
System.out.println(loginSuccess ? "登陸成功" : "登陸失敗");
}