3

I have a table on sql with the following data:

name  location
sarah   
dave     
bob     
rover
dave
bob
emma
john
prash

I have some data coming in that gives me location details of all these people. The locations could either be:

name_data  location_data
sarah          GB 
dave           US
bob            FR
rover          IN
dave           US
bob            FR
emma           ES
john           NI

How do I update the database so I can include the locations relative to the name? I tried the following, but it didn't seem to work:

cursor.execute("UPDATE "+table_name+"location) values (?)",location_data"WHERE name like" "'"name_data"'")
1
  • Judging by the (?) I'm guessing this uses sqlite syntax? That is a badly distorted string you're trying to build. If table_name needs to be dynamic then perhaps break it into two parts; first build a query= string in which you use %s for the parts that cannot be represented by (?) and then execute the query string and add the values covered by placeholders in the execution stage Commented Mar 14, 2016 at 18:38

3 Answers 3

7
name=input("Enter name:")

loc = input("Enter Location:")  
cursor = cnxn.cursor() 
SQLCommand = ("UPDATE {table_name} SET location_data=?  WHERE name_data ="+ name+" ")
Location = [loc]
cursor.execute(SQLCommand,Location) 
Sign up to request clarification or add additional context in comments.

Comments

3

If you pack name/location data in list of tuples:

for name, location in name_location_data:
    sql = "UPDATE {tbl} SET location=? WHERE name=?".format(tbl=table_name)
    cursor.execute(sql, name, location)

Comments

-1

I think the '(?)' representation for strings won't work when updating a table. I suggest you use '%s' and SET. It should look something like this:

cursor.execute("UPDATE table_name SET location='%s' WHERE name='%s'" % (location_data, name_data))

2 Comments

You actually can use '?' with UPDATE - stackoverflow.com/a/28071336/706751
This is exactly something that must NEVER be done! Unescaped value in location_data or name_data opens your code for a SQL-injection attack. Solution is to use ?-binding.

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.