PyMySQL 使用笔记

本文详细介绍了使用pymysql库进行数据库连接,特别是connections模块的Connection类和cursors模块的Cursor类,涵盖了如何创建连接、执行SQL、事务管理等关键操作。实例演示了如何通过配置参数连接数据库,并展示了Cursor的不同类型及其应用。
摘要由CSDN通过智能技术生成

1. connections 模块

类:Connection
用法:执行 pymysql.connect() 得到。而不是构造函数 Connection()。
pymysql.connect() 的参数即为 Connection() 构造函数的参数。
构造函数:

pymysql.connections.Connection(self,
    host=None,          # 要连接的主机地址
    user=None,          # 用于登录的数据库用户
    password='',        # 密码
    database=None,      # 要连接的数据库
    port=0,             # 端口,一般为 3306
    unix_socket=None,   # 选择是否要用unix_socket而不是TCP/IP
    charset='',         # 字符编码
    sql_mode=None,      # Default SQL_MODE to use.
    read_default_file=None, # 从默认配置文件(my.ini或my.cnf)中读取参数
    conv=None,          # 转换字典
    use_unicode=None,   # 是否使用 unicode 编码
    client_flag=0,      # Custom flags to send to MySQL. Find potential values in constants.CLIENT.
    cursorclass=<class 'pymysql.cursors.Cursor'>, # 选择 Cursor 类型
    init_command=None,  # 连接建立时运行的初始语句 
    connect_timeout=10, # 连接超时时间,(default: 10, min: 1, max: 31536000)
    ssl=None,           # A dict of arguments similar to mysql_ssl_set()'s parameters.For now the capath and cipher arguments are not supported. 
    read_default_group=None, # Group to read from in the configuration file.
    compress=None,      # 不支持
    named_pipe=None,    # 不支持
    no_delay=None,      # 
    autocommit=False,   # 是否自动提交事务
    db=None,            # 同 database,为了兼容 MySQLdb
    passwd=None,        # 同 password,为了兼容 MySQLdb
    local_infile=False, # 是否允许载入本地文件
    max_allowed_packet=16777216, # 限制 `LOCAL DATA INFILE` 大小
    defer_connect=False, # Don't explicitly connect on contruction - wait for connect call.
    auth_plugin_map={}, #
    read_timeout=None,  # 
    write_timeout=None, 
    bind_address=None   # 当客户有多个网络接口,指定一个连接到主机
    )

重要函数

函数说明
cursor(cursor=None)创建一个游标
commit()事务提交,如果没有设为自动提交,则每次操作后必须提交事务,否则操作无效。
rollback()操作出错时,可以用这个函数回滚到执行事务之前
close()关闭连接
  • 一个例子
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)

2. cursors 模块

类 : Cursor
使用 connections.Connection.cursor() 得到,而不是这个类的构造函数。
connections.Connection.cursor()的参数是 cursor 的类型。

重要函数

函数说明
callproc(procname, args=())执行一个过程
execute(query,args=None)执行一条SQL语句,返回受影响的行数。若args是列表,用%s做占位符,若是字典,用%(name)s
executemany(query,args)对一个操作运行多个数据,如一次插入多条数据
fetchall()取出操作返回的所有的行接
fetchone()取出一行
fetchmany(size=None)取出 size 行
close()关闭这个游标对象
  • 游标类型
类名说明
Cursor默认类型,查询返回list
DictCursor与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}
  • 一个例子
#!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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值