本文共 2612 字,大约阅读时间需要 8 分钟。
当使用 MySQLdb 进行数据库查询时,默认情况下会返回元组类型的结果集。这种类型的数据虽然便于内存存储,但在实际应用中往往不够灵活,特别是在需要处理结构化数据时。例如,以下代码执行后会返回一个元组:
import MySQLdbdb = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='test')cur = db.cursor()cur.execute('select * from user')rs = cur.fetchall()print(rs) # 返回结果类似于:# ((1000L, 0L), (2000L, 0L), (3000L, 0L))
为了解决上述限制,可以引入 DictCursor 类,这样查询结果将转换为字典格式,方便数据处理和展示。具体实现如下:
import MySQLdbimport MySQLdb.cursorsdb = MySQLdb.connect( host='localhost', user='root', passwd='123456', db='test', cursorclass=MySQLdb.cursors.DictCursor)cur = db.cursor()cur.execute('select * from user')rs = cur.fetchall()print(rs) # 返回结果类似于:# [{'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 3000L}] 如果已经有现有的连接,可以单独更改 cursor 类型:
db = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='test')cur = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
import pymysqldbdb = pymysqldb.connect("localhost", "root", "123456", "filestore")cursor = db.cursor()sql = 'select * from tablelist where id > %s' % 4result = cursor.execute(sql).fetchall()print('result:', result)sql2 = 'select * from tablelist where id > %s'values = ('4',) # 使用元组类型result2 = cursor.execute(sql2, values).fetchall()print('result2:', result2)# 提取数据并存储到列表中id_list = []tablename_list = []tabletime_list = []result3 = cursor.execute('select * from tablelist where id > %s', [4]).fetchall()print('type(result3):', type(result3))for row in result3: id_list.append(row[0]) tabname = row[1] tabletime = row[2] tabtime_list.append(tabletime) tabname_list.append(tabname)print('id_list:', id_list)print('tablename_list:', tabname_list)print('tabletime_list:', tabtime_list) # 结果为元组类型:# ((6, 'engineeringdata20180901', '1535731200'), (618, 'engineeringdata20180904', '1535990400'))
# 使用 list 获取结果list = []get_list = 'select * from tablelist where id > %s'list = cursor.execute(get_list, [4]).fetchall()# 提取数据并存储到列表中for row in list: print('当前行:', row) list_id.append(row['id']) list_tablename.append(row['tablename']) list_tabletime.append(row['tabletime'])print('list_id:', list_id)print('list_tabletime:', list_tabletime)print('list_tablename:', list_tablename) # 结果为列表类型:# [{'id': 6, 'tablename': 'engineeringdata20180901', 'tabletime': '1535731200'}, # {'id': 618, 'tablename': 'engineeringdata20180904', 'tabletime': '1535990400'}] 通过引入 DictCursor,我们可以将默认的元组类型结果转换为更灵活的字典类型,方便数据处理和展示。无论是直接修改连接方式还是单独更改 cursor 类型,都能实现预期的结果。选择合适的方法根据具体需求进行操作,以提升开发效率和用户体验。
转载地址:http://mvofk.baihongyu.com/