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;
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();
}
}
After entering the correct user name and password, it will prompt "Login successful"
When the user name or password is entered incorrectly, the prompt "User name or password is incorrect, please re-enter"
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"
Using the splicing method, SQL will also appear Syntax errors and other errors, such as
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 programimport 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();
}
}
When the username or password is entered incorrectly, it will prompt "The username or password is incorrect, please re-enter"
According to the previous situation, write SQL injection. After the test, SQL injection will no longer occur.
After using the preprocessing class, inputting content with single quotes or double quotes will not work SQL syntax errors will appear again
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!

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.

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.

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

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.

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.

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.
