1. 程式人生 > >JDBC防止SQL攻擊之PreparedStatement的用法

JDBC防止SQL攻擊之PreparedStatement的用法

public boolean login(String username, String passwo)

throws Exception {

/*

* 一、得到Connection 二、得到Statement 三、得到ResuleSet 四、rs.next()返回的是什麼,就返回什麼

*/

// 準備四大引數

String driverClassName = "com.mysql.jdbc.Driver";

String url = "jdbc:mysql://localhost:3306/mydb3";

String mysqlUsername = "root";

String mysqlPassword = "12345678";

// 載入驅動類

Class.forName(driverClassName);

// 得到Connection

Connection con = DriverManager.getConnection(url, mysqlUsername,

mysqlPassword);

/*

* 一、得到preparedStatement 1.給出sql模版:所有的引數使用?代替

* 2.呼叫Connection方法,得到PreparedStatement

*/

String sql = "select * from t_user where username=? and password=?";

PreparedStatement pstmt = con.prepareStatement(sql);

/*

* 二、為引數賦值

*/

pstmt.setString(1, username);// 給第1個問號賦值,值為username

pstmt.setString(2, passwo);// 給第二個問號賦值,值為password

ResultSet rs = pstmt.executeQuery();// 呼叫查詢方法,向資料庫傳送查詢語句

return rs.next();

}