Last active
October 3, 2020 01:49
-
-
Save dustyfresh/7324aae41217bc00663d8fc61f553e9d to your computer and use it in GitHub Desktop.
dump mysql table as jsonl file
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
#!/usr/bin/env python | |
import json | |
import pymysql.cursors | |
def main(): | |
# Connect to the database | |
connection = pymysql.connect( | |
host='localhost', | |
user='changeme', | |
password='changeme', | |
db='changeme', | |
charset='utf8mb4', | |
cursorclass=pymysql.cursors.SSDictCursor # we use SSDictCursor for streaming rows (saves ram) | |
) | |
try: | |
with open('table.json', 'a+') as f: | |
cursor = connection.cursor() | |
sql = 'select * from `table`;' | |
relnum = cursor.execute(sql) | |
result = cursor.fetchone() | |
while result is not None: | |
db_record = {} | |
for k,v in result.items(): | |
db_record[k] = v | |
# Write to json outfile | |
f.write(f'{json.dumps(db_record)}\n') | |
result = cursor.fetchone() | |
finally: | |
cursor.close() | |
connection.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment