Skip to content

Instantly share code, notes, and snippets.

@dustyfresh
Last active October 3, 2020 01:49
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 dustyfresh/7324aae41217bc00663d8fc61f553e9d to your computer and use it in GitHub Desktop.
Save dustyfresh/7324aae41217bc00663d8fc61f553e9d to your computer and use it in GitHub Desktop.
dump mysql table as jsonl file
#!/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