1

I'm attempting to insert some variables into a MySQL database using python. Sometimes the variables will be strings and sometimes they will be None.

A hugely simplified version of what I am attempting is below:

import MySQLdb as mdb
f = "Bob"
m = None
l = "Smith"

db = mdb.connect("blah blah blah")
with db:
    cur.execute("INSERT INTO name (first, middle, last) VALUES ('{0}', '{1}', '{2}')".format(f, m, l))

The problem is that it inserts 'None' as a string rather than as an actual NULL value.

I can solve the problem by changing the last line to:

cur.execute("INSERT INTO name (first, middle, last) VALUES (%s, %s, %s)", (f, m, l))

but I believe that this leaves the code vulnerable to MySQL injection attacks. If anyone knows the correct way using the .format method I would be very grateful.

3
  • No, the string formatting leaves you vulnerable. Passing values the second way is what is expected. Commented Jun 25, 2015 at 15:12
  • Thanks - I'm glad I got my apology for the dumb question in early Commented Jun 25, 2015 at 15:13
  • Its not a dumb question. Its important you know how to protect against SQL injection. Commented Jun 25, 2015 at 15:14

1 Answer 1

1

The expected method of inserting data is the following:

cur.execute("INSERT INTO name (first, middle, last) VALUES (%s, %s, %s)", (f, m, l))

Formatting a string like in your first example leaves your application vulnerable to SQL injection.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. Neither deprecated %, nor .format will not work in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.