The code that returns the dictionary structure when Python queries Mysql
- 2020-04-02 09:40:45
- OfStack
MySQLdb default query results are returned to tuple, output is not very convenient, must be read according to 0,1, inadvertently found a simple modification method on the web, is passed a cursors.
Default program:
MySQLdb default query results are returned to tuple, output is not very convenient, must be read according to 0,1, inadvertently found a simple modification method on the web, is passed a cursors. Default program:
# returns something like this
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))
Revised:
# returns something like this
# ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 2000L}) or the connect and cursor parts can be replaced with the following
Default program:
MySQLdb default query results are returned to tuple, output is not very convenient, must be read according to 0,1, inadvertently found a simple modification method on the web, is passed a cursors. Default program:
import MySQLdb
db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´)
cursor = db.cursor()
cursor.execute(´select * from table´)
rs = cursor.fetchall()
print rs
# returns something like this
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))
Revised:
import MySQLdb
import MySQLdb.cursors
db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´,cursorclass = MySQLdb.cursors.DictCursor)
cursor = db.cursor()
cursor.execute(´select * from table´)
rs = cursor.fetchall()
print rs
# returns something like this
# ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 2000L}) or the connect and cursor parts can be replaced with the following
db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´)
cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)