Last active
August 29, 2015 14:24
-
-
Save critmcdonald/32a52745275d9ecdb2c2 to your computer and use it in GitHub Desktop.
Using Python Dataset to udpate mysql data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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