/*
*
* sql注入:數據庫對用戶傳入的參數進行了編輯,改變了原本的sql的結構
* 預編譯:在用戶傳入參數之前先進行編譯,確定sql的結構,在傳入用戶的參數執行
* 1.select count(*) from user where username = ? and password = ?;
* 對於參數部分使用佔位符?
* 2.編譯完畢之後,確定了結構才傳入參數
* 3.對於用戶傳入的特殊字符參數,使用轉義,變成沒有實際意義的字符
*
* 預編譯操作對象的獲取api:
* PreparedStatement prepareStatement(String sql) 創建一個 PreparedStatement對象,用於將參數化的SQL語句發送到數據庫。
* */
1.executeQuery()方法,主要用DQL語句
public class LoginDemo {
public static void main(String[] args) throws SQLException {
Connection connection = JdbcUtil.getConnection();
String sql = "SELECT count(*) FROM USER WHERE username = ? AND password = ? ;";
//1.在用戶傳入參數之前先進行編譯,確定sql的結構
PreparedStatement statement = connection.prepareStatement(sql);
//2.預編譯完畢之後,再傳入用戶的參數
statement.setString(1,username);
statement.setString(2,password);
//3.執行sql即可
ResultSet resultSet = statement.executeQuery(); //注意:預編譯時,sql不用再傳,之前已經傳遞過了
int count = 0;
while (resultSet.next()) {
count = resultSet.getInt("count(*)");
}
System.out.println(count >0 ? "登錄成功" :" 登錄失敗");
JdbcUtil.release(resultSet,statement,connection);
}
}
2.executeUpdate()方法,主要用於DML語句(update,delete,insert)
public class CRUDDemo {
@Test
public void insertTest() throws SQLException {
Connection connection = JdbcUtil.getConnection();
//使用預編譯進行數據的插入
String sql = "INSERT into USER VALUES (?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,6);
statement.setString(2,"liubei");
statement.setString(3,"123456");
int executeUpdate = statement.executeUpdate();
System.out.println(executeUpdate);
JdbcUtil.release(null,statement,connection);
}
}