简体   繁体   中英

Updating fields on a Microsoft SQL Table using pyodbc - Python

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"'")
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) 

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)

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM