您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
07-JDBC-API详解-PreparedStatement(预处理)
发布时间:2024-11-13 22:46:26编辑:雪饮阅读()
-
sql注入就是用占位符?来代替原本的字符串拼接,改用PreparedStatement进行填充参数,而填充的时候内部的逻辑肯定就是类似对该占位的值进行转义以及mysql关键字等的匹配处理。所以规避了sql注入。
那么我们可以将上篇中的sql注入再次实现用PreparedStatement实现看看
@Test
public void testPreparedStatement() throws Exception {
String url="jdbc:mysql://192.168.217.132/demo?useSSL=false";
String username="root";
String password="1448169a3cb137d7";
Connection conn= DriverManager.getConnection(url,username,password);
Statement stmt=conn.createStatement();
String userName="张三";
String userPassword="123";
String userPassword2="' or '1' = '1";
String sql8="select * from user where name = ? and password = ?";
PreparedStatement pstmt=conn.prepareStatement(sql8);
pstmt.setString(1,userName);
pstmt.setString(2,userPassword);
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
System.out.println("登录成功");
}
pstmt.setString(2,userPassword2);
rs=pstmt.executeQuery();
if(rs.next()){
System.out.println("注入登录成功");
}
rs.close();
stmt.close();
conn.close();
}
这次的 输出就仅仅只是非注入的密码才能成功登录。
关键字词:PreparedStatement,预处理