Skip to content

Instantly share code, notes, and snippets.

@critmcdonald
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save critmcdonald/32a52745275d9ecdb2c2 to your computer and use it in GitHub Desktop.
Save critmcdonald/32a52745275d9ecdb2c2 to your computer and use it in GitHub Desktop.
Using Python Dataset to udpate mysql data
"""
This script uses the datatset library to udpate data in a mysql/mariadb database.
In this use case, I'm taking the field RaceSex (Example: 'White Male')
and updating the Race field with the first letter of the first word
and updating the Gender field with the first letter of the last word
If RaceSex is null or blank, a 'U' is used.
"""
import dataset
db = dataset.connect('mysql://USER:PASSWORD@HOST/database_name')
table = db['table_name']
for row in enumerate(table):
# try makes exceptions for null and blank field
try:
split_parts = row['RaceSex'].split(' ')
gender = split_parts[-1:][0][0]
race = row['RaceSex'][0]
except (AttributeError, IndexError):
gender = 'U'
race = 'U'
row['Gender'] = gender
row['Race'] = race
table.update(row, ['id'])
print("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment