JDBC 初級登陸密碼驗證

2021-10-23 14:45:31 字數 2279 閱讀 6764

1. 輸入資料

該功能目的為實現使用者輸入的字串與資料庫中已有的字串匹配,從而登陸資料庫,簡單實現一下。

scanner input =

newscanner

(system.in)

;system.out.

println

("***************歡迎來到該系統***************===");

system.out.

println

("***************請輸入使用者名稱:***************===");

string username = input.

nextline()

;system.out.

println

("***************請輸入密碼:********************====");

string pwd = input.

nextline()

;

2. jdbc連線
//註冊驅動

class.

forname

("com.mysql.jdbc.driver");

// 獲得連線

string url =

"jdbc:mysql://localhost:3306/gp2003?usessl=false&charecterencoding=utf8"

;connection conn = drivermanager.

getconnection

(url,

"root"

,"root@123456"

);

3. 進行對比操作

3.1 使用statement執行

statement:用於執行靜態 sql 語句並返回它所生成結果的物件。

// 建立命令

statement stat = conn.

createstatement()

;// 執行命令

resultset rs = stat.

executequery

("select * from student where name ='"

+ username +

"' and password = '"

+ pwd +

"';");

// 遍歷

if(rs.

next()

)else

note:

此種寫法會出現乙個小bug,當輸入使用者名稱+』#1=1(例如: user』#1=1)時,雖然資料庫內並沒有該資料,但是特意登陸成功。

原因:資料庫內預設語句select * from users where user_name=』『or 1=1』 and password=』$password』 ,有or在,使用者名稱不管輸入什麼,只要最後加上』#1=1便可登入成功,這是使用statement的弊端。

解決方式:使用preparedstatement進行sql預編譯。

3.2 使用preparedstatement執行操作

preparedstatement:表示預編譯的 sql 語句的物件,繼承了statement介面,執行sql語句的方法無異。

jdbc中的所有引數都由 ?符號佔位,這被稱為引數標記。

在執行sql語句之前,必須為每個引數提供值。

// 對name和password進行預編譯,使用?佔位

preparedstatement pstat = conn.

preparestatement

("select * from student where name = ? and password = ?");

// 給佔位符賦值

pstat.

setstring(1

, username)

;pstat.

setstring(2

, pwd)

;resultset rs = pstat.

executequery()

;if(rs.

next()

)else

4. 關閉資源

由小到大,依次關閉資源。

// 使用哪個便關閉哪個

rs.close()

;pstat.

close()

;conn.

close()

;

mysql登陸找回密碼 MySql登陸密碼找回

在windows下 開啟命令列視窗,停止mysql服務 net stop mysql 啟動mysql,一般到mysql的安裝路徑,找到 mysqld nt.exe 或mysqld.exe 執行 mysqld nt 或mysqld.exe skip grant tables 當前視窗將會停止。另外開啟...

Linux mysql忘記登陸密碼

centos7 mysql忘記密碼處理方法 1.修改mysql的登入設定 3.登入並修改mysql的root密碼 mysql use mysql mysql update user set password password new password where user root mysql fl...

jupyter登陸密碼設定

1.首先開啟anaconda prompt 輸入 jupyter notebook generate config 出現如下 填y,生成以下檔案 c users 曉寧.jupyter jupyter notebook config.py 1 2.回到anaconda prompt 輸入 jupyte...