热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

JDBC中使用preparedStatement解决SQL注入的问题

JDBC中使用preparedStatement解决SQL注入的问题今天学习JDBC的时候老师讲到了使用Statement会产生sql注入的问题,并且讲了解决方案&#

JDBC中使用preparedStatement解决SQL注入的问题


今天学习JDBC的时候老师讲到了使用Statement会产生sql注入的问题,并且讲了解决方案,所以写在这里和大家一起学习
下面我记录得东西都是比较基础的,如果是大佬,不喜勿喷[/抱拳]!如有错误,也欢迎指正!
话不多说,开整:


先看张图
在这里插入图片描述
账号和密码我是随便输入的,但是他却显示登陆成功了,这是怎么回事呢?
主要问题出在以下这行代码中

//获取数据操作对象
statement = connection.createStatement();
//执行SQL
String sql = "select * from t_user where loginName = '"+initializeTheInterface.get("logginName")+"' and loginPwd = '"+initializeTheInterface.get("logginPwd")+"'";
resultSet = statement.executeQuery(sql);

当我们在动态获取账户和密码的时候,如果我们输入的是可以干扰到查询语句的字符,那么在上面这行语句的执行的时候,查询就会出现故障,这时即使输入错误的密码也能登录成功;举个例子:

当我们输入以上的这串密码时候,其实也就相当于把这句sql语句变成了:“select * from t_user where loginName = fdsa and loginPwd = fdsa or “1”=1“,那么这时这个语句必然成立,查询成功。
这也就是sql注入的根本原因所在!

下面是使用Statement连接数据库的代码:

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;/** @Auther:sunny_wwu* @Data:2022-04-15 8:39* @Description:JDBC* @Version:1.0* @Detail:* */
public class Log {public static void main(String[] args) {/*Initialize the interface,create a method for entering the user name and password,and return the assignment to“initializeTheInterface”*/Map<String,String> initializeTheInterface &#61;initializeTheInterface();/*Verify the username and password,compare the entered username and password through the login method,return the result as boolean type, and assign the verification result to“logginsuccess”*/boolean logginSuccess &#61; login(initializeTheInterface);/*output login result*/System.out.println(logginSuccess ? "登录成功" : "登录失败");}/*** Compare with the database user name and password Check* whether the user name and password are correct* &#64;param initializeTheInterface Username and password entered by the user* &#64;return Compare the results, return true for success, false for failures*/private static boolean login(Map<String, String> initializeTheInterface) {//打标记boolean logginSuccess &#61; false;//JDBC 代码Connection connection &#61; null;Statement statement &#61; null;ResultSet resultSet &#61; null;try {//注册驱动Class.forName("com.mysql.jdbc.Driver");//获取连接connection &#61; DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bgpowernode","root","123456");//获取数据操作对象statement &#61; connection.createStatement();//执行SQLString sql &#61; "select * from t_user where loginName &#61; &#39;"&#43;initializeTheInterface.get("logginName")&#43;"&#39; and loginPwd &#61; &#39;"&#43;initializeTheInterface.get("logginPwd")&#43;"&#39;";resultSet &#61; statement.executeQuery(sql);//处理结果集if (resultSet.next()){//登录成功logginSuccess &#61; true;}} catch (ClassNotFoundException | SQLException e) {e.printStackTrace();}finally {//关闭资源if (resultSet !&#61; null) {try {resultSet.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (statement !&#61; null) {try {statement.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (connection !&#61; null) {try {connection.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}return logginSuccess;}/*** Initialize the login interface* &#64;return entered user&#39;s username and password*/private static Map<String, String> initializeTheInterface() {Scanner scanner &#61; new Scanner(System.in);System.out.print("用户名:");String logginName &#61; scanner.nextLine();System.out.print("密码:");String logginPwd &#61; scanner.nextLine();Map<String,String> userLogginInfo &#61; new HashMap<>();userLogginInfo.put("logginName",logginName);userLogginInfo.put("logginPwd",logginPwd);return userLogginInfo;}
}

针对本程序的sql注入解决方案

这里我们是使用preparedStatement&#xff08;预编译Statement&#xff09;来解决的。
preparedStatement&#xff08;预编译Statement&#xff09;接口它是继承了java。sql.Statement&#xff0c;属于预编译的数据库操作对象&#xff0c;其原理是预先编译sql语句的框架&#xff0c;然后再给sql语句传“值”&#xff0c;那么由此一来&#xff0c;即使传进去带有sql敏感的词汇&#xff0c;也不会扭曲语句的意思。

其中最大的改变就是下面的几行代码&#xff1a;

String sql &#61; "select * from t_user where loginName &#61; ? and loginPwd &#61; ?";
preparedStatement &#61; connection.prepareStatement(sql);
//给占位符传值&#xff0c;第一个问号下标是1&#xff0c;第二个问号下标是2.......
preparedStatement.setString(1,initializeTheInterface.get("logginName"));
preparedStatement.setString(2,initializeTheInterface.get("logginPwd"));
//执行SQL
resultSet&#61; preparedStatement.executeQuery();

在这里我们不难看出&#xff0c;使用占位符先构成查询完成之后&#xff0c;再由preparedStatement的setString方法把值传进去&#xff0c;这样bug就解决了。这里需要解释以下“&#xff1f;”作为占位符&#xff0c;他只是一个代表&#xff0c;不参加预编译&#xff0c;只是后来查询的时候通过传进来的值进行查询的。另外&#xff0c;setString方法的第一个参数是int类型的数子&#xff0c;代表的是第几个占位符&#xff0c;第二个是要传进去的String值。

下面是改进之后的完全代码&#xff0c;其他地方也有些许改动&#xff0c;请仔细看完。

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/** &#64;Auther:sunny_wwu* &#64;Data:2022-04-16 9:48* &#64;Description:JDBC-com* &#64;Version&#xff1a;1.1* &#64;Detail&#xff1a;Solve the vulnerability that the program can be injected by SQL* */
public class log02 {public static void main(String[] args) {/*Initialize the interface,create a method for entering the user name and password,and return the assignment to“initializeTheInterface”*/Map<String,String> initializeTheInterface &#61;initializeTheInterface();/*Verify the username and password,compare the entered username and password through the login method,return the result as boolean type, and assign the verification result to“logginsuccess”*/boolean logginSuccess &#61; login(initializeTheInterface);/*output login result*/System.out.println(logginSuccess ? "登录成功" : "登录失败");}/*** Compare with the database user name and password Check* whether the user name and password are correct* &#64;param initializeTheInterface Username and password entered by the user* &#64;return Compare the results, return true for success, false for failures*/private static boolean login(Map<String, String> initializeTheInterface) {//打标记boolean logginSuccess &#61; false;//JDBC 代码Connection connection &#61; null;PreparedStatement preparedStatement &#61; null;ResultSet resultSet &#61; null;try {//注册驱动Class.forName("com.mysql.jdbc.Driver");//获取连接connection &#61; DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bgpowernode","root","123456");//获取数据操作对象//statement &#61; connection.createStatement();String sql &#61; "select * from t_user where loginName &#61; ? and loginPwd &#61; ?";preparedStatement &#61; connection.prepareStatement(sql);//给占位符传值&#xff0c;第一个问号下标是1&#xff0c;第二个问号下标是2.......preparedStatement.setString(1,initializeTheInterface.get("logginName"));preparedStatement.setString(2,initializeTheInterface.get("logginPwd"));//执行SQLresultSet&#61; preparedStatement.executeQuery();//处理结果集if (resultSet.next()){//登录成功logginSuccess &#61; true;}} catch (ClassNotFoundException | SQLException e) {e.printStackTrace();}finally {//关闭资源if (resultSet !&#61; null) {try {resultSet.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (preparedStatement !&#61; null) {try {preparedStatement.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (connection !&#61; null) {try {connection.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}return logginSuccess;}/*** Initialize the login interface* &#64;return entered user&#39;s username and password*/private static Map<String, String> initializeTheInterface() {Scanner scanner &#61; new Scanner(System.in);System.out.print("用户名:");String logginName &#61; scanner.nextLine();System.out.print("密码:");String logginPwd &#61; scanner.nextLine();Map<String,String> userLogginInfo &#61; new HashMap<>();userLogginInfo.put("logginName",logginName);userLogginInfo.put("logginPwd",logginPwd);return userLogginInfo;}}

总结

面对上面的修改&#xff0c;那是不是说Statement就完全不需要了呢&#xff1f;

其实不是&#xff0c;有的项目也可能会要求允许sql注入&#xff0c;比如项目中有说明要求sql语句拼接的要求&#xff0c;这时Statement就起到作用了
总之&#xff0c;针对这边文章&#xff0c;我们总结为以下几点


对比一下statement和preparedStatement&#xff1f;

  • 后者存在sql注入的问题&#xff0c;前者解决了sql注入的问题&#xff1b;
  • 前者是编译一次执行一次&#xff0c;后者是编译一次&#xff0c;可执行N次&#xff0c;这样效率会高一点&#xff1b;
  • 后者会在编译阶段做类型的安全检查&#xff1b;
  • 前者使用较多&#xff0c;但是在极少数的情况下也是需要用到后者的&#xff1b;
  • 业务方面要求需要进行sql语句拼接的&#xff0c;可使用Statement&#xff1b;

最后&#xff0c;感谢您能看到这里&#xff0c;如果您觉得文章对您有些帮助的话&#xff0c;还请帮忙点点赞&#xff0c;如果您有不同意见也可以在下面评论区一起讨论。


推荐阅读
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了一个Java猜拳小游戏的代码,通过使用Scanner类获取用户输入的拳的数字,并随机生成计算机的拳,然后判断胜负。该游戏可以选择剪刀、石头、布三种拳,通过比较两者的拳来决定胜负。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文介绍了Java高并发程序设计中线程安全的概念与synchronized关键字的使用。通过一个计数器的例子,演示了多线程同时对变量进行累加操作时可能出现的问题。最终值会小于预期的原因是因为两个线程同时对变量进行写入时,其中一个线程的结果会覆盖另一个线程的结果。为了解决这个问题,可以使用synchronized关键字来保证线程安全。 ... [详细]
  • 本文介绍了一个在线急等问题解决方法,即如何统计数据库中某个字段下的所有数据,并将结果显示在文本框里。作者提到了自己是一个菜鸟,希望能够得到帮助。作者使用的是ACCESS数据库,并且给出了一个例子,希望得到的结果是560。作者还提到自己已经尝试了使用"select sum(字段2) from 表名"的语句,得到的结果是650,但不知道如何得到560。希望能够得到解决方案。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • Android源码深入理解JNI技术的概述和应用
    本文介绍了Android源码中的JNI技术,包括概述和应用。JNI是Java Native Interface的缩写,是一种技术,可以实现Java程序调用Native语言写的函数,以及Native程序调用Java层的函数。在Android平台上,JNI充当了连接Java世界和Native世界的桥梁。本文通过分析Android源码中的相关文件和位置,深入探讨了JNI技术在Android开发中的重要性和应用场景。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 本文介绍了Oracle存储过程的基本语法和写法示例,同时还介绍了已命名的系统异常的产生原因。 ... [详细]
author-avatar
我并没有你们想象P的坚强
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有