2

Trying to build an SQL statement for execute. This works but now sure how pythonic it might be:

user_fields = ("id", "name", "email", "password", "phone")

fields = [field for field in user_fields if field != "id"]  # The only field we don't want is "id"
percent_s = ["%s"] * len(fields)
fields = ",".join(fields)
percent_s = ",".join(percent_s)

sql = "INSERT INTO user_table (" + fields + ") VALUES (" + percent_s + ")"
cursor.execute(sql, row_data)
3
  • Before anyone reflexively screams "SQL injection", note that what's being concatenated is just a list of placeholders. Commented Aug 24, 2015 at 0:42
  • IMO this is a deficiency of the Python DB-API. It should specify a placeholder like %P or something, which inserts a number of comma-separated placeholders equal to the number of query parameters passed. A variant that lets you specify how many placeholders as a parameter would also be nice. Commented Aug 24, 2015 at 0:47
  • I like portions of both answers so far. With regards to "%s" being visually confusing in the sense of one potentially thinking "Oh no! SQL Injection!" I like @rofls answer with the idea of using {} and .format. In other words, I am currently seeing it mostly as a visual differentiator. Commented Aug 24, 2015 at 21:24

2 Answers 2

1

You could replace:

sql = "INSERT INTO user_table (" + fields + ") VALUES (" + percent_s + ")"

with

sql = "INSERT INTO user_table ({}) VALUES ({})".format(fields,percent_s)
Sign up to request clarification or add additional context in comments.

Comments

1

If your user_fields has a fixed order, row_data must have a corresponding order. You have to ensure this somewhere. Then the position of id is also fixed. Then you can use string formatting, which leads to:

user_fields = ("id", "name", "email", "password", "phone")

sql = "INSERT INTO user_table (%s) VALUES (%s)" % (','.join(user_fields[1:], ','.join(['%s'] * (len(user_fields) - 1))
cursor.execute(sql, row_data)

Comments

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.