Sourz
Sourz

Reputation: 18

How to update the value of a specific column of every row in DB with the output of a function that was passed in the original value.

For example: if you wanted to replace in each row the value of a column with the value after being run through a hash function.

In my case I have saved many URLs in a column that have 302 redirects and I want to save where they redirect to after passing their current value into this function:

def finalURL(original):
    output = requests.get(original)
    output.url
    return output.url

I am relatively new to Python and the closest examples I can find are not written in Python (cannot translate).

Additionally I've seen several posts on how to iterate through a db and print every value in a column, but no explanation on how to change that value.

Upvotes: 0

Views: 29

Answers (1)

CL.
CL.

Reputation: 180080

To make your hash function available in SQLite, you have to create a user-defined function:

def finalURL(x):
    return ...

db = sqlite3.connect(...)
db.create_function("finalURL", 1, finalURL)

Then you can simply use it in queries:

db.execute("UPDATE MyTable SET url = finalURL(url) WHERE ...")

Upvotes: 1

Related Questions