- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is SQL injection? How can you prevent it?
SQL injection is a web hacking technique. It is the code injection technique which inserts malicious code into your database and destroys the database. This is the insertion of malicious code via web page input.
The main cause of SQL injection is providing data smartly into the SQL query which manipulates the data inside our database.
Suppose we have a table with students data. Each student can view his own data using his student id. The SQL query is designed such that it takes the student id input from the student.
Now, the student can enter his student id as “12345 or 1=1”. This translates into the followinq query.
SELECT * FROM Students WHERE id==12345 or 1=1
Now, the above query will return records of other students as well because 1=1 is always true. Hence, the data is of other students is not safe and prone to misuse by the hackers.
The Mysql connector module has method to escape query values in order to prevent SQL injection. The query values can be escaped using the placeholder %s.
Suppose, we have a table named “MyTable”.
+----------+---------+-----------+------------+ | Name | Class | City | Marks | +----------+---------+-----------+------------+ | Karan | 4 | Amritsar | 95 | | Sahil | 6 | Amritsar | 93 | | Kriti | 3 | Batala | 88 | | Khushi | 9 | Delhi | 90 | | Kirat | 5 | Delhi | 85 | +----------+---------+-----------+------------+
import mysql.connector db=mysql.connector.connect(host="your host", user="your username", password="your password",database="database_name") cursor=db.cursor() query="SELECT * FROM Students WHERE Name=%s" name=("Karan",) cursor.execute(query,name) for row in myresult: print(row)
The above code shows the use of placeholders to escape query values.
(‘Karan’, 4, ‘Amritsar’ , 95)
- What is Code Injection? (How it Works, How to Prevent)
- What Is Doxing and How Can You Prevent It?
- What is SQL Injection?
- What is Bloatware and how can you remove it?
- What is IUD? How does it prevent pregnancy?
- What is Bluesnarfing and how to prevent it?
- What is spear phishing and how can you avoid it?
- What is Harpooning? (How it Works, How to Prevent)
- What is Credential Stuffing? (How it Works, How to Prevent)
- What is Hacking and how is it performed? How to prevent hacking?
- What is Rogue Security Software? (Features, What It Does, How to Prevent)
- What is Heartbleed Bug? (How it Works, Vulnerable Devices, How to Prevent
- What is dependency injection in PHP?
- How can closures cause memory leak and how to prevent it?
- What is Information Fatigue Syndrome? How does it affect you?