gython
gython

Reputation: 875

Is there a way to update a database table with a python dictionary?

I am trying to write data back into the column of a database table.

The data is stored in a python dictionary, because I need the key to identify the row I want to update.

Here a snippet of my code so far:

l = []
for line in text:
    soup = bs(line, 'html.parser')

    for script in soup(["script", "style"]):
        script.extract() 

    autor = soup.get_text()

    s = autor.replace('\n', '')
    l.append(s)

dictW = dict(zip(t,l))

sql = 'UPDATE tablename SET Reintext WHERE = ...'
cursor.executemany(sql, dictW)

dictW looks like this :

{'file:/C:/Users/125.html' : 'long string of a html file'}

I am stuck at the UPDATE statement.

How can I write it to update the database table with the values in the dictionary while using the keys as identifier?

Upvotes: 0

Views: 1678

Answers (1)

OneCrazyGenius
OneCrazyGenius

Reputation: 52

for key in dictW:
    x = dictW[key]
    print(key, x)

This look gives you key and value separately so you can use them in your SQL statement. This will iterate through your dictionary so you can get a list of keys and values separately for your SQL statement

sql = 'UPDATE tablename SET Reintext WHERE ? = ? '
cursor.executemany(sql, (key, x))

Upvotes: 1

Related Questions