InterviewSolution
| 1. |
What do you understand by SQL injection? What is the prescribed method of executing parameterized queries using DB-API? |
|
Answer» SQL injection is the technique of inserting malicious SQL statements in the user input thereby gaining unauthorized access to database and causing harm in an interactive data driven application. Most computer applications including Python applications that involve database interaction use relational database products that work on SQL queries. Python has standardized database adapter specifications by DB-API standard. Python standard distribution has sqlite3 module which is a DB-API compliant SQLite driver. For other databases the module must be installed. For example, if using MySQL, you will have to install PyMySQL module. Standard procedure of EXECUTING SQL queries is to first establish connection with database SERVER, obtain cursor object and then execute SQL query string. Following describes the sequence of steps for SQLite database con=sqlite3.connect(‘testdata.db’) cur=con.cursor() cur.execute(SQLQueryString)For example, following code displays all records in products table whose category is ‘Electronics’ qry=”SELECT * from products where ctg==’Electronics’;”However, if price is taken as user input then the query string will have to be constructed by inserting user input variable. CATG=input(‘enter category:’) qry=”select * from prooducts where ctg={};”.format(catg)if input is Electronics, the query will be built as select * from products where ctg=’Electronics’But a malicious input such as following is given enter category:electronics;drop table products;Now this will cause the query to be as follows:
In such prepared statements, database engine checks validity of interpolated data and MAKES sure that undesirable query is not executed, preventing SQL injection attack. |
|