JDBC連線mysql資料庫操作

2022-08-24 00:57:13 字數 1654 閱讀 8151

一.建立所需物件,並進行初始化

connection connection=null;

statement statement=null;

preparedstatement pst;

resultset rs=null;

二.載入mysql驅動

class.forname("com.mysql.jdbc.driver");
三.建立鏈結(url為資料庫連線,root帳號,pwd密碼)

connection=drivermanager.getconnection(url,root,pwd);
四.建立statement一般建立為預編形的即preparedstatement,如果使用statement會引起sql注入攻擊,首先是一般的statement:

statement=connection.createstatement();

string sql="select * from user where username='"+username+"'"+"and password='"+password+"'";

rs=statement.executequery(sql);

if(rs.next())

else

五.測試:1.輸入正確帳號="張三",密碼=1234;獲得效果

2.輸入錯誤帳號=12312,密碼=1231234' or '1'='1;獲得效果,並將sql語句列印出來

3.總結:這句sql相當與( select * from user)一般的stament會因為sql拼接的問題,可能會被惡意攻擊,攻擊者可以無需帳號密碼即可登入,可甚至可以刪除你的資料庫。

六.使用preparedstatement防止sql注入,增強安全性,而且他比statement的效率更高,因為它是預先編譯好的sql語句,使用?來代表引數,通過pst.setstring方法將值傳入,

第乙個引數代表是第幾個?的位置(從1開始),第二個引數代表是引數值。

string sql="select * from user where username=? and password=?";

pst=connection.preparestatement(sql);

pst.setstring(1, username);

pst.setstring(2, password);

system.out.println(pst.tostring());

rs=pst.executequery();

if(rs.next())

else

七.測試:輸入錯誤帳號=12312,密碼=1231234' or '1'='1(sql注入方法能否正常登入)

八.總結,為什麼能防止sql,看列印出來的sql語句便可以知道,預編譯的語句在執行時會自動轉義一些字元,從而防止sql注入

jdbc 連線mysql資料庫

class.forname org.postgresql.driver newinstance 裝載資料庫驅動 string url jdbc postgresql localhost 5432 postgres connection con drivermanager.getconnection ...

JDBC 連線MYSQL資料庫

1.載入驅動 class.forname com.mysql.jdbc.driver com.mysql.jdbc 包名 driver 驅動名,驅動包需要引入進來 mysql com.mysql.jdbc.driver oracle oracle.jdbc.driver.oracledriver s...

JDBC連線MySQL資料庫

在學習jdbc過程中,用idea連線資料庫時出現的問題記錄,來來回回找了好多資料,現在把相應的解決辦法記錄下來。通過localhost連線mysql資料庫時,可能會遇到時區的問題,簡單設定一下就可以了,但是通過localhost一般都是可以連上的。string url jdbc mysql loca...