search
HomeDatabaseSQLLearn about SQL injection and how to fix it

Learn about SQL injection and how to fix it

Recommendation (free): sql tutorial

##SQL injection refers to the intrusion of user-entered data by web applications. There is no judgment on legality or lax filtering. Attackers can add additional SQL statements at the end of the predefined query statements in the web application to achieve illegal operations without the administrator's knowledge, thereby deceiving the database. The server performs unauthorized arbitrary queries to further obtain corresponding data information.

1. SQL injection case

Simulate a SQL injection case of user login. The user enters the user name and password on the console, and then uses Statement string concatenation. Implement user login.

1.1 First create the user table and data in the database

-- 创建一张用户表
CREATE TABLE `users` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(20),
  `password` VARCHAR(50),
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;


-- 插入数据
INSERT INTO  users(username,`password`) VALUES('张飞','123321'),('赵云','qazxsw'),('诸葛亮','123Qwe');
INSERT INTO  users(username,`password`) VALUES('曹操','741258'),('刘备','plmokn'),('孙权','!@#$%^');


-- 查看数据
SELECT  * FROM users;

Learn about SQL injection and how to fix it

##1.2 Write a login Program

import java.sql.*;
import java.util.Scanner;


public class TestSQLIn {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=UTF-8";
        Connection conn = DriverManager.getConnection(url,"root","123456");
        //System.out.println(conn);
        // 获取语句执行平台对象 Statement
        Statement smt = conn.createStatement();


        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String userName = sc.nextLine();
        System.out.println("请输入密码:");
        String password = sc.nextLine();


        String sql = "select  * from users where username = '" + userName + "'  and  password = '" + password +"'";
        //打印出SQL
        System.out.println(sql);
        ResultSet resultSet = smt.executeQuery(sql);
        if(resultSet.next()){
            System.out.println("登录成功!!!");
        }else{
            System.out.println("用户名或密码错误,请重新输入!!!");
        }


        resultSet.close();
        smt.close();
        conn.close();


    }


}

1.3 Normal login

After entering the correct user name and password, it will prompt "Login successful"

Learn about SQL injection and how to fix it

1.4 Login failure

When the user name or password is entered incorrectly, the prompt "User name or password is incorrect, please re-enter"

Learn about SQL injection and how to fix it

1.5 Simulating SQL injection

The concatenated string contains or '1'='1', which is a constant condition, so even if the previous user and password do not exist, it will All records are taken out, so the prompt "Login successful"

Learn about SQL injection and how to fix it

1.6 SQL syntax error

Using the splicing method, SQL will also appear Syntax errors and other errors, such as

Learn about SQL injection and how to fix it

2. Solution

Using the Statement method, the user can change the original text through string splicing. The true meaning of SQL leads to the risk of SQL injection. To solve SQL injection, you can use the preprocessing object PreparedStatement instead of Statement for processing.

1.1 Write a new program

import java.sql.*;
import java.util.Scanner;


public class TestSQLIn {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=UTF-8";
        Connection conn = DriverManager.getConnection(url,"root","123456");
        //System.out.println(conn);
        // 获取语句执行平台对象 Statement
        // Statement smt = conn.createStatement();


        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String userName = sc.nextLine();
        System.out.println("请输入密码:");
        String password = sc.nextLine();


        String sql = "select  * from users where username = ? and  password = ? ";
        // System.out.println(sql);
        // ResultSet resultSet = smt.executeQuery(sql);
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1,userName);
        preparedStatement.setString(2,password);


        ResultSet  resultSet = preparedStatement.executeQuery();
        if(resultSet.next()){
            System.out.println("登录成功!!!");
        }else{
            System.out.println("用户名或密码错误,请重新输入!!!");
        }




        preparedStatement.close();
        resultSet.close();
        // smt.close();
        conn.close();


    }


}

2.2 Log in normally

Learn about SQL injection and how to fix it

2.3 Incorrect username and password

When the username or password is entered incorrectly, it will prompt "The username or password is incorrect, please re-enter"

Learn about SQL injection and how to fix it

2.4 Simulate SQL injection

According to the previous situation, write SQL injection. After the test, SQL injection will no longer occur.

Learn about SQL injection and how to fix it

2.5 Simulating SQL syntax error

After using the preprocessing class, inputting content with single quotes or double quotes will not work SQL syntax errors will appear again

Learn about SQL injection and how to fix it

3. Summary

The main differences between Statement and PreparedStatement are as follows:

    Statement is used to execute static SQL statements. During execution, a prepared SQL statement must be specified.
  • PrepareStatement is a precompiled SQL statement object. The statement can contain the dynamic parameter "?", and the parameter value can be dynamically set for "?" during execution
  • PrepareStatement can reduce the number of compilations and improve database performance

The above is the detailed content of Learn about SQL injection and how to fix it. 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
MySQL: A Practical Application of SQLMySQL: A Practical Application of SQLMay 08, 2025 am 12:12 AM

MySQL is popular because of its excellent performance and ease of use and maintenance. 1. Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2. Insert and query data: operate data through INSERTINTO and SELECT statements. 3. Optimize query: Use indexes and EXPLAIN statements to improve performance.

Comparing SQL and MySQL: Syntax and FeaturesComparing SQL and MySQL: Syntax and FeaturesMay 07, 2025 am 12:11 AM

The difference and connection between SQL and MySQL are as follows: 1.SQL is a standard language used to manage relational databases, and MySQL is a database management system based on SQL. 2.SQL provides basic CRUD operations, and MySQL adds stored procedures, triggers and other functions on this basis. 3. SQL syntax standardization, MySQL has been improved in some places, such as LIMIT used to limit the number of returned rows. 4. In the usage example, the query syntax of SQL and MySQL is slightly different, and the JOIN and GROUPBY of MySQL are more intuitive. 5. Common errors include syntax errors and performance issues. MySQL's EXPLAIN command can be used for debugging and optimizing queries.

SQL: A Guide for Beginners - Is It Easy to Learn?SQL: A Guide for Beginners - Is It Easy to Learn?May 06, 2025 am 12:06 AM

SQLiseasytolearnforbeginnersduetoitsstraightforwardsyntaxandbasicoperations,butmasteringitinvolvescomplexconcepts.1)StartwithsimplequerieslikeSELECT,INSERT,UPDATE,DELETE.2)PracticeregularlyusingplatformslikeLeetCodeorSQLFiddle.3)Understanddatabasedes

SQL's Versatility: From Simple Queries to Complex OperationsSQL's Versatility: From Simple Queries to Complex OperationsMay 05, 2025 am 12:03 AM

The diversity and power of SQL make it a powerful tool for data processing. 1. The basic usage of SQL includes data query, insertion, update and deletion. 2. Advanced usage covers multi-table joins, subqueries, and window functions. 3. Common errors include syntax, logic and performance issues, which can be debugged by gradually simplifying queries and using EXPLAIN commands. 4. Performance optimization tips include using indexes, avoiding SELECT* and optimizing JOIN operations.

SQL and Data Analysis: Extracting Insights from InformationSQL and Data Analysis: Extracting Insights from InformationMay 04, 2025 am 12:10 AM

The core role of SQL in data analysis is to extract valuable information from the database through query statements. 1) Basic usage: Use GROUPBY and SUM functions to calculate the total order amount for each customer. 2) Advanced usage: Use CTE and subqueries to find the product with the highest sales per month. 3) Common errors: syntax errors, logic errors and performance problems. 4) Performance optimization: Use indexes, avoid SELECT* and optimize JOIN operations. Through these tips and practices, SQL can help us extract insights from our data and ensure queries are efficient and easy to maintain.

Beyond Retrieval: The Power of SQL in Database ManagementBeyond Retrieval: The Power of SQL in Database ManagementMay 03, 2025 am 12:09 AM

The role of SQL in database management includes data definition, operation, control, backup and recovery, performance optimization, and data integrity and consistency. 1) DDL is used to define and manage database structures; 2) DML is used to operate data; 3) DCL is used to manage access rights; 4) SQL can be used for database backup and recovery; 5) SQL plays a key role in performance optimization; 6) SQL ensures data integrity and consistency.

SQL: Simple Steps to Master the BasicsSQL: Simple Steps to Master the BasicsMay 02, 2025 am 12:14 AM

SQLisessentialforinteractingwithrelationaldatabases,allowinguserstocreate,query,andmanagedata.1)UseSELECTtoextractdata,2)INSERT,UPDATE,DELETEtomanagedata,3)Employjoinsandsubqueriesforadvancedoperations,and4)AvoidcommonpitfallslikeomittingWHEREclauses

Is SQL Difficult to Learn? Debunking the MythsIs SQL Difficult to Learn? Debunking the MythsMay 01, 2025 am 12:07 AM

SQLisnotinherentlydifficulttolearn.Itbecomesmanageablewithpracticeandunderstandingofdatastructures.StartwithbasicSELECTstatements,useonlineplatformsforpractice,workwithrealdata,learndatabasedesign,andengagewithSQLcommunitiesforsupport.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.