Skip to content

Instantly share code, notes, and snippets.

@pepijnblom
Created December 24, 2019 08:22
Show Gist options
  • Save pepijnblom/cad31e8aff77f5d527c3d4c850d970e7 to your computer and use it in GitHub Desktop.
Save pepijnblom/cad31e8aff77f5d527c3d4c850d970e7 to your computer and use it in GitHub Desktop.
mysql query to json
import mysql.connector as mysql
import simplejson as json
import sys
def cursor_to_dict(cursor):
data = cursor.fetchone()
if data is None:
return None
desc = cursor.description
result = {}
for (name, value) in zip(desc, data):
result[name[0]] = value
return result
db = mysql.connect(
host = "127.0.0.1",
user = "root",
passwd = "root",
database = "database",
port = "3306"
)
cursor = db.cursor()
## defining the Query
query = """
SELECT
*
FROM
table
WHERE
1=1
"""
cursor.execute(query)
sys.stdout.write('[')
row = cursor_to_dict(cursor)
first_line = True
while row is not None:
if first_line == True:
first_line = False
else:
sys.stdout.write(',')
json_str = json.dumps(row, default=str)
sys.stdout.write(json_str)
row = cursor_to_dict(cursor)
sys.stdout.write(']')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment