PreparedStatement作用:①预编译SQL语句并执行:预防SQL注入问题
SQL注入:是通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法
登录逻辑(用"+xxx+"进行字符串拼接):
(使用SQL注入时,username随便输入,pwd输入' or '1' = ' 1会显示登录成功)
(打印sql语句,会得到select id,username,password from user where username ='自己输入的' and password = '' or '1' = '1')
(此时password为username and password(false) ∪'1' = '1'(true),此操作即为sql注入)
import java.sql.*;
public class test {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://127.0.0.1:3306/db1?useSLL=false";
String name = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, name, password);
String username = "jack";
String pwd = "247893";
//定义SQL语句,用"+xxx+"进行拼接
String sql = "select id,username,password from user where username = '"+username+"' and password = '"+pwd+"'";
//获取stmt对象
Statement stmt = conn.createStatement();
//执行SQL
ResultSet rs = stmt.executeQuery(sql);
//判断是否成功,能查出数据即成功
if(rs.next()){
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
rs.close();
conn.close();
stmt.close();
}
}
网友评论