search
HomeDatabaseSQLTroubleshooting SQL injection issues

Troubleshooting SQL injection issues

Jan 12, 2021 am 09:22 AM
sql injection

<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/052/5ffcf9b492b47340.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Troubleshooting SQL injection issues" >

Recommended (free):<a href="https://www.php.cn/sql/" target="_blank">SQL tutorial</a>

SQL What is injection?

Look at the definition of Baidu Encyclopedia:
Troubleshooting SQL injection issues
Ah, it’s such a long paragraph. I don’t want to read it. Let’s use an example to explain what SQL injection is. :

Create a new database, create a table, and add two rows of data:

use db1;create table user(
	id int primary key auto_increment,
	username varchar(32),
	password varchar(32));insert into user values(null,'zhangsan','123');insert into user values(null,'lisi','234');

The table is as shown below:
Troubleshooting SQL injection issues
Use it casually JDBCWrite a login operation:

package com.wzq.jdbc;import com.wzq.util.JDBCUtils;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Scanner;/*
 *   需求:
 *       1、通过键盘录入用户名和密码
 *       2、判断用户是否登陆成功
 * */public class JDBCDemo05 {

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = cin.nextLine();
        System.out.println("请输入密码:");
        String password = cin.nextLine();

        boolean res = new JDBCDemo05().login(username, password);
        if (res) System.out.println("登陆成功!");
        else System.out.println("登陆失败!");

    }

    public boolean login(String username, String password) {
        if (username == null || password == null) {
            return false;
        }
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //1、获取数据库连接
            conn = JDBCUtils.getConnection();   //JDBCUtils工具类
            //2、定义sql
            String sql = "select * from user where username = '" + username + "' and password = '" + password + "'";
            //3、获取执行sql的对象
            stmt = conn.createStatement();
            //4、执行sql
            rs = stmt.executeQuery(sql);
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(rs, stmt, conn);
        }
        return false;
    }}

Test it:
Troubleshooting SQL injection issues
You can see that there is no problem with the ordinary test. Now use SQL injection:

Enter the account name casually, enter the password: a' or 'a'='a
Troubleshooting SQL injection issues
I was surprised to find that the login was successful. Output sql and take a look:

select * from user where username = 'askjdhjksahd' and password = 'a' or 'a' = 'a'

You can see the conditions after where. No matter what result is true, the entire table will be output:
Troubleshooting SQL injection issues
So, to sum up: when splicing sql, some sql special keywords participate in string splicing, which will cause security problems. This This is the reason why the login is successful above.


So how to solve this problem?

Answer: Use the PreparedStatement object instead of the Statement object.

PreparedStatement object is a subclass of Statement object. It is precompiled sql, so it runs faster than StatemnetFaster.

PerpaerdStatementUse ? as a placeholder and use setXxx(index, value) to assign a value## to ?

#So let’s replace

Statement and write the code:

    public boolean login(String username, String password) {        if (username == null || password == null) {            return false;
        }
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {            //1、获取数据库连接
            conn = JDBCUtils.getConnection();   //JDBCUtils类
            //2、定义sql
            String sql = "select * from user where username = ? and password = ?";
            //3、获取执行sql的对象
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            //4、执行sql
            rs = pstmt.executeQuery();
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(rs, pstmt, conn);
        }        return false;
    }
Test it:


Troubleshooting SQL injection issues Successfully solved!

The above is the detailed content of Troubleshooting SQL injection issues. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
SQL in Action: Real-World Examples and Use CasesSQL in Action: Real-World Examples and Use CasesApr 18, 2025 am 12:13 AM

In practical applications, SQL is mainly used for data query and analysis, data integration and reporting, data cleaning and preprocessing, advanced usage and optimization, as well as handling complex queries and avoiding common errors. 1) Data query and analysis can be used to find the most sales product; 2) Data integration and reporting generate customer purchase reports through JOIN operations; 3) Data cleaning and preprocessing can delete abnormal age records; 4) Advanced usage and optimization include using window functions and creating indexes; 5) CTE and JOIN can be used to handle complex queries to avoid common errors such as SQL injection.

SQL and MySQL: Understanding the Core DifferencesSQL and MySQL: Understanding the Core DifferencesApr 17, 2025 am 12:03 AM

SQL is a standard language for managing relational databases, while MySQL is a specific database management system. SQL provides a unified syntax and is suitable for a variety of databases; MySQL is lightweight and open source, with stable performance but has bottlenecks in big data processing.

SQL: The Learning Curve for BeginnersSQL: The Learning Curve for BeginnersApr 16, 2025 am 12:11 AM

The SQL learning curve is steep, but it can be mastered through practice and understanding the core concepts. 1. Basic operations include SELECT, INSERT, UPDATE, DELETE. 2. Query execution is divided into three steps: analysis, optimization and execution. 3. Basic usage is such as querying employee information, and advanced usage is such as using JOIN connection table. 4. Common errors include not using alias and SQL injection, and parameterized query is required to prevent it. 5. Performance optimization is achieved by selecting necessary columns and maintaining code readability.

SQL: The Commands, MySQL: The EngineSQL: The Commands, MySQL: The EngineApr 15, 2025 am 12:04 AM

SQL commands are divided into five categories in MySQL: DQL, DDL, DML, DCL and TCL, and are used to define, operate and control database data. MySQL processes SQL commands through lexical analysis, syntax analysis, optimization and execution, and uses index and query optimizers to improve performance. Examples of usage include SELECT for data queries and JOIN for multi-table operations. Common errors include syntax, logic, and performance issues, and optimization strategies include using indexes, optimizing queries, and choosing the right storage engine.

SQL for Data Analysis: Advanced Techniques for Business IntelligenceSQL for Data Analysis: Advanced Techniques for Business IntelligenceApr 14, 2025 am 12:02 AM

Advanced query skills in SQL include subqueries, window functions, CTEs and complex JOINs, which can handle complex data analysis requirements. 1) Subquery is used to find the employees with the highest salary in each department. 2) Window functions and CTE are used to analyze employee salary growth trends. 3) Performance optimization strategies include index optimization, query rewriting and using partition tables.

MySQL: A Specific Implementation of SQLMySQL: A Specific Implementation of SQLApr 13, 2025 am 12:02 AM

MySQL is an open source relational database management system that provides standard SQL functions and extensions. 1) MySQL supports standard SQL operations such as CREATE, INSERT, UPDATE, DELETE, and extends the LIMIT clause. 2) It uses storage engines such as InnoDB and MyISAM, which are suitable for different scenarios. 3) Users can efficiently use MySQL through advanced functions such as creating tables, inserting data, and using stored procedures.

SQL: Making Data Management Accessible to AllSQL: Making Data Management Accessible to AllApr 12, 2025 am 12:14 AM

SQLmakesdatamanagementaccessibletoallbyprovidingasimpleyetpowerfultoolsetforqueryingandmanagingdatabases.1)Itworkswithrelationaldatabases,allowinguserstospecifywhattheywanttodowiththedata.2)SQL'sstrengthliesinfiltering,sorting,andjoiningdataacrosstab

SQL Indexing Strategies: Improve Query Performance by Orders of MagnitudeSQL Indexing Strategies: Improve Query Performance by Orders of MagnitudeApr 11, 2025 am 12:04 AM

SQL indexes can significantly improve query performance through clever design. 1. Select the appropriate index type, such as B-tree, hash or full text index. 2. Use composite index to optimize multi-field query. 3. Avoid over-index to reduce data maintenance overhead. 4. Maintain indexes regularly, including rebuilding and removing unnecessary indexes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor