PreparedStatement的应用
PreparedStatement:是Statement的子接口,可以传入带占位符的SQL语句,提供了补充占位符变量的方法
可以防止SQL注入
SQL注入指的是通过构建特殊的输入作为参数传入Web应用程序,而这些输入大都是SQL语法里的一些组合,通过执行SQL语句进而执行攻击者所要的操作,其主要原因是程序没有细致地过滤用户输入的数据,致使非法数据侵入系统。
//获得preparedStatement对象 预编译SQL语句
PreparedStatement preparedStatement = connection.prepareStatement("select * from user " +
"where username = ? and password = ?");
System.out.println(preparedStatement);
打印preparedStatement对象,有一个预编译的过程,得:
com.mysql.cj.jdbc.ClientPreparedStatement: select * from user where
username = ** NOT SPECIFIED ** and password = ** NOT SPECIFIED **
使用NOT SPECIFIED占用需要赋值得位置。
赋值方法:
再次打印该对象:
com.mysql.cj.jdbc.ClientPreparedStatement: select * from user where
username = ‘abc’ or 1=1; #’ and password = ‘12345’
这时就不难发现无论你输入什么样的字符,都会被当作字符填充到?占位符的位置,就解决SQL注入的问题。
代码展示:
/*
* PreparedStatement的应用(解决SQL注入导致的密码失效问题)
* */
package JavaPrepard;
import java.sql.*;
import java.util.Scanner;
public class LoginJdbc2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名称:");
String username = scanner.nextLine();
System.out.println("请输入用户密码:");
String password = scanner.nextLine();
//加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
//获得链接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true" +
"&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8","root","123456");
//获得preparedStatement对象 预编译SQL语句
PreparedStatement preparedStatement = connection.prepareStatement("select * from user " +
"where username = ? and password = ?");
System.out.println(preparedStatement);
//为?占位符 赋值
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
System.out.println(preparedStatement);
//执行sql语句,接收结果
ResultSet resultset = preparedStatement.executeQuery();
//结果处理
if(resultset.next()){
System.out.println("登录成功!!!");
}else{
System.out.println("登录失败!!!");
}
//释放资源
resultset.close();
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
写在最后:
作者:小兰学编程(一个学编程的一年级新生)
更多内容请关注公众号:小兰小栈
欢迎各位大神指点一二!!!