这个感觉写的挺全面,免得以后自己再找
原文地址:https://blog.csdn.net/memoryd/article/details/74995651
- 一个例子
import pymysql.cursors config = { 'host':'127.0.0.1', 'port':3306, 'user':'root', 'password':'xinxin2333', 'database':'trade_ms', 'charset':'utf8mb4', 'cursorclass':pymysql.cursors.Cursor, } # 连接数据库 connection = pymysql.connect(**config) 1234567891011121314- 游标类型
类名说明Cursor默认类型,查询返回listDictCursor与Cursor不同的地方是,查询返回dict,包括属性名SSCursor查询不会返回所有的行,而是按需求返回SSDictCursor差别同前两个 举例说明 #Cursor 查询返回 (10000, 't恤男短袖', 28, Decimal('89.00'), 300) #DictCursor 查询返回 {'cid': 10000, 'cname': 't恤男短袖', 'claid': 28, 'price': Decimal('89.00'), 'cnum': 300} 1234 一个例子 #!python3 #-*- coding: utf-8 -*- import pymysql.cursors # 好像import这个模块就可以了 config = { 'host':'127.0.0.1', 'port':3306, 'user':'root', 'password':'xinxin2333', 'database':'trade_ms', 'charset':'utf8mb4', 'cursorclass':pymysql.cursors.Cursor, } connection = pymysql.connect(**config) # 连接数据库 try: with connection.cursor() as cursor: sql = 'SELECT * FROM commodity WHERE price > 100 ORDER BY price' count = cursor.execute(sql) # 影响的行数 print(count) result = cursor.fetchall() # 取出所有行 for i in result: # 打印结果 print(i) connection.commit() # 提交事务 except: connection.rollback() # 若出错了,则回滚 finally: connection.close()