How to get all mysql tuple result and convert to json

I managed to get individual data from the table. but when I try to get all the data on my table, I have only one row.

cnn.execute(sql)
        rows = cnn.fetchall()
        column = [t[0] for t in cnn.description]
        for row in rows:
            myjson = {column[0]: row[0], column[1]: row[1], column[2]: row[2], column[3]: row[3], column[4]: row[4], column[5]: row[5], column[6]: row[6], column[7]: row[7], column[8]: row[8], column[9]: row[9], column[10]: row[10], column[11]: row[11], column[12]: row[12], column[13]: row[13], column[14]: row[14], column[15]: row[15], column[16]: row[16], column[17]: row[17], column[18]: row[18], column[19]: row[19], column[20]: row[20]}
            myresult = json.dumps(myjson, indent=3)
            return myresult
+4
source share
5 answers

Now, in PyMysql, it is possible to configure your connection to use cursorClass, which by default generates a dictionary as output. (And thus it works directly, returning to the API result when it is converted to JSON)

From PyMysql documentation : configure your connection as

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

result = cursor.fetchone()
        print(result)

Result for this result:

{'password': 'very-secret', 'id': 1}
+7
source

" " , zip() ( itertools.izip()).

, json:

def dictfetchall(cursor):
    """Returns all rows from a cursor as a list of dicts"""
    desc = cursor.description
    return [dict(itertools.izip([col[0] for col in desc], row)) 
            for row in cursor.fetchall()]

:

results = dictfetchall(cursor)
json_results = json.dumps(results)

, .

+4

Your return statement is inside the for loop, so after one iteration it will immediately return with a value myresult.

+1
source

Yes, @metatoaster is right,

Try the following:

cnn.execute(sql)
    rows = cnn.fetchall()
    column = [t[0] for t in cnn.description]
    for row in rows:
        myjson = {column[0]: row[0], column[1]: row[1], column[2]: row[2], column[3]: row[3], column[4]: row[4], column[5]: row[5], column[6]: row[6], column[7]: row[7], column[8]: row[8], column[9]: row[9], column[10]: row[10], column[11]: row[11], column[12]: row[12], column[13]: row[13], column[14]: row[14], column[15]: row[15], column[16]: row[16], column[17]: row[17], column[18]: row[18], column[19]: row[19], column[20]: row[20]}
        myresult = json.dumps(myjson, indent=3)
    return myresult
0
source
#imports 
import collections
import MySQLdb
import json

#connect to database
conn = MySQLdb.connect(host= "localhost", user="root", passwd="abc",  db="mydatabase")

#Fetch rows
sql  = "SELECT * from userstable"
cursor = conn.cursor()
cursor.execute(sql)
data = cursor.fetchall()

#Converting data into json
user_list = []
for row in data :
    d = collections.OrderedDict()
    d['firstName']  = row[1] #name
    d['lastName']   = row[2] #lname
    d['email']      = row[3] #email
    user_list.append(d)

return json.dumps(user_list)


##Result
[{"firstName":"jame","lastName":"king","email":"test@gmail.com"}]
0
source

Source: https://habr.com/ru/post/1531089/


All Articles