Python MySQLDB: Get the result of fetchall in a list

前端 未结 7 1458
攒了一身酷
攒了一身酷 2020-12-01 07:24

I would like to get the result of the fetchall operation in a list instead of tuple of tuple or tuple of dictionaries. For example,

cursor = connection.cur         


        
7条回答
  •  鱼传尺愫
    2020-12-01 08:03

    I'm sure that after all this time, you've solved this problem, however, for some people who may not know how to get the values of a cursor as a dictionary using MySQLdb, you can use this method found here:

    import MySQLdb as mdb
    
    con = mdb.connect('localhost', 'testuser', 'test623', 'testdb')
    
    with con:
    
        cur = con.cursor(mdb.cursors.DictCursor)
        cur.execute("SELECT * FROM Writers LIMIT 4")
    
        rows = cur.fetchall()
    
        for row in rows:
            print row["Id"], row["Name"]
    

提交回复
热议问题