2

I'd like to be able to update multiple SQLite database rows given a list of columns and a list of lists of data. I have a working solution, but it's not elegant at all. How can I do this more efficiently. I've left out the actual UPDATE statement as I am just focusing on building the query.

def update(columns, values):
    for value in values:
        print ("Update myTable SET " + " ".join([x + ' = "%s",' for x in columns]) + ' WHERE SSN = "%s"').replace(", WHERE", " WHERE") % (tuple(value))

columns = ['Name', 'Age']
values  = [['Jon', 12, '545-45-7987'], ['Sam', 13, '454-78-4545']]

update(columns, values)

1 Answer 1

2

You shouldn't be interpolating values for your UPDATE; rather you should be using placeholders and query parameters. This will avoid quoting complications and potential SQL injection vulnerabilities. Something like:

def update(cursor, columns, values):
    for value in values:
        sql = "UPDATE myTable SET {} WHERE ssn = ?".format(
            ", ".join(map("{} = ?".format, columns)))
        print(sql)
        cursor.execute(sql, values)      

columns = ['Name', 'Age']
values  = [['Jon', 12, '545-45-7987'], ['Sam', 13, '454-78-4545']]
cursor = conn.cursor()  
update(cursor, columns, values)
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. Much cleaner!
One comment. I think SQLite uses ? as a placeholder rather than %s
@user2242044 Then why did you use %s in your question?
@Cubic: %s in the question is not a placeholder; it's a conversion specifier for the python's string formatting operator %.

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.