Hello fellow python lovers of daniweb.com. This isn't as much a question as much as the fact that I want to see how different people would go about using python to inject an SQl database. I made a script were you can access the ip and run a command. NOTE:Obviously I didn't give an actual database. Who am I kidding you guys aren't stupid. Here's my injection script

import MySQLdb

db = MySQLdb.connect(host="localhost", # your host, usually localhost
                     user="USER", # your username
                      passwd="PWD", # your password
                      db="MySQLdb") # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor() 
2 Years
Discussion Span
Last Post by Schol-R-LEA

Actually, you've misunderstood what the term 'SQL injection' means, and fortunately for you, your script doesn't involve any. All your code does is open a connection to a MySQL database server and create a cursor, the basic steps interacting with a database.

SQL injection is a (bad) way of building a SQLquery string, in which user input is inserted directly to a text query string and then executed:

name = raw_input("What is your name?")
cur.execute("SELECT * FROM Students WHERE Name = '%s';" % name)

The reason this is a bad idea is the same reason while it was a bad idea to use input() in Python 2.x: because the user could put anything into the input, not just their name, and the 'data' will get executed along with the query. For example, if I entered Robert'; DROP TABLE Students; --, the final query string would read

"SELECT * FROM Students WHERE Name = 'Robert'; DROP TABLE Students; --';"

which would wreak havoc on the database.

The way to avoid SQL injection is to use a prepared statement, which is a feature of the database that vetts the data automatically for you, making the above scenario less likely.

name = raw_input("What is your name?")
cur.execute("SELECT * FROM Students WHERE Name = %s;", (name))     

This may seem like a trivial difference, but when using the prepared statement, the database checks the validity of the interpolated data, making sure that the cannot execute undesireable code.

BTW: the mysqldb library hasn't been updated since June 2013, and only works with Python 2.x. The preferred way to interact with MySQL nowadays is the MySQL Connector/Python, which is provided by the MySQL team themselves.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.