python连接mysql的一个常用库------pymysql

pymysql

一、概要

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,

二、PyMySQL 安装

pip install pymysql

三、操作流程

  1. 创建connection
  2. 获取cursor
  3. 执行增删改查的操作
  4. 处理数据
  5. 关闭cursor
  6. 关闭connection

四、核心类介绍

1、创建connection

  1. 说明

  2. 语法格式

    conn = pymysql.connect(host=None, user=None, password="",
                     database=None, port=0, db=None,charset='')
    
  3. 常用参数说明

    参数名 类型 说明
    host String MySQL的服务器地址
    port int MySQL的端口号
    user String 用户名
    passwd String 密码
    db String 使用的数据库
    charset String 连接字符集
  4. 返回值

    cursor

  5. 示例代码

    HOST = '127.0.0.1'
    PORT = 3306
    USER = 'root'
    PASSWD = 'root'
    DB = 'python'
    CHARSET = 'utf8'
    
    connection = pymysql.connect(host=HOST,
                                 port=PORT,
                                 user=USER,
                                 passwd=PASSWD,
                                 db=DB,
                                 charset=CHARSET)
    
    
  6. 其它方法

    方法 描述
    begin() 开启事务
    commit() 提交事务
    cursor(cursor=None) 创建一个游标用来执行语句
    ping(reconnect=True) 检查连接是否存活,会重新发起连接
    rollback() 回滚事务
    close() 关闭连接
    select_db(db) 选择数据库
    show_warnings() 查看warning信息
  7. 详细

    • host – 数据库服务器所在的主机。
    • user – 登录用户名。
    • password – 登录用户密码。
    • database – 连接的数据库。
    • port – 数据库开放的端口。(默认: 3306)
    • bind_address – 当客户端有多个网络接口时,请指定连接到主机的接口,参数可以是主机名或IP地址。
    • unix_socket – 使用unix套接字而不是tcp/ip。
    • charset – 连接字符集。
    • sql_mode – 默认SQL模式。
    • read_default_file – 指定my.cnf文件路径,以便从[client]部分读取参数。
    • conv – 要使用的转换字典,而不是默认值。
    • use_unicode – 是否默认为unicode字符串,对于Py3k,此选项默认为true。
    • client_flag – 发送到MySQL的自定义标志。
    • cursorclass – 使用自定义的游标类。
    • init_command – 建立连接时要运行的初始SQL语句。
    • connect_timeout – 建立连接超时时间。(默认: 10,最小: 1,最大: 31536000)
    • read_default_group – 从配置文件中读取组。
    • compress – 不支持
    • named_pipe – 不支持
    • autocommit – 设置自动提交模式,不设置意味着使用数据库默认。(默认值: False)
    • local_infile – 是否启用“LOAD LOCAL INFILE”命令的使用。(默认值: False)
    • max_allowed_packet – 发送到服务器的数据包的最大大小 (以字节为单位,默认值: 16MB),仅用于限制小于默认值 (16KB) 的 “LOAD LOCAL INFILE” 数据包的大小。
    • defer_connect – 不要显式连接建设,等待连接调用。(默认值: False)
    • db – 连接数据库别名(兼容MySQLdb)
    • passwd – 密码输入别名(兼容MySQLdb)
    • binary_prefix – 在bytes和bytearray上添加_binary前缀(默认: False)

2、获取cursor对象

  1. 说明

    游标对象,用于执行查询和获取结果

  2. 核心方法

    方法名 说明
    execute() 用于执行一个数据库的查询命令
    fetchone() 获取结果集中的下一行
    fetchmany(size) 获取结果集中的下(size)行
    fetchall() 获取结果集中剩下的所有行
    rowcount 最近一次execute返回数据/影响的行数
    close() 关闭游标
  3. 举个栗子

    1、执行查询功能

    with connection.cursor() as cursor:
        sql = 'select * from home_user'
        cursor.execute(sql)
        results = cursor.fetchall()
        connection.commit()
        for results in results:
            uid = results[0]
            name = results[1]
            password = results[2]
            print('==========用户信息===============')
            print('用户id: {id} \n用户名: {name}\n密码: {pwd}'.format(id=uid, name=name, pwd=password))
    
  4. 详细

    方法 描述
    close() 关闭游标。
    execute(query, args=None) 执行单条语句,传入需要执行的语句,是string类型;同时可以给查询传入参数,参数可以是tuple、list或dict。执行完成后,会返回执行语句的影响行数,如果有的话。
    executemany(query, args) 执行多条INSERT语句,传入需要执行的语句;同时可以给查询传入参数,参数是一个mappings序列。执行完成后,会返回执行语句的影响行数,如果有的话。
    fetchone() 获取下一行数据。
    fetchall() 获取所有数据。
    fetchmany(size=None) 获取几行数据。
    read_next() 获取下一行数据。
    callproc() 用来调用存储过程。
    mogrify() 参数化查询,防止SQL注入。
    scroll(num,mode) 移动游标位置。

五、基本操作

查询数据

  1. 分页查询操作

    def find_by_page(page, size):
        with pymysql.connect(host=HOST,
                             port=PORT,
                             user=USER,
                             passwd=PASSWORD,
                             charset=CHARSET,
                             db=DB_NAME) as cursor:
            sql = "SELECT * FROM t_addr LIMIT{},{}".format((page - 1) * size, size)
            cursor.execute(sql)
            users = cursor.fetchall()
    

事务操作

  1. 示例代码

    conn = pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='root',
        database='python',
        charset='utf8'
    )
    
    cursor = conn.cursor()
    
    # 插入sql;
    sql_insert = "insert into t_user (userid,username) values (10,'user10')"
    # 更新sql;
    sql_update = "update t_user set username = 'name91' where userid=9"
    # 删除sql;
    sql_delete = "delete from t_user where userid < 3"
    
    # 把一个事务放到一个try块里,如果出现异常就回滚;
    try:
        # 开启事务;
        conn.begin()
        cursor.execute(sql_insert)
        print(cursor.rowcount)
    
        cursor.execute(sql_update)
        print(cursor.rowcount)
    
        cursor.execute(sql_delete)
        print(cursor.rowcount)
    
        # 提交事务;
        conn.commit()
    
    except Exception as e:
        # 若有异常就回滚;
        conn.rollback()
    
    cursor.close()
    conn.close()
    

批量插入

  1. 示例代码

    # 测试事务 批量添加
    def test_batch_insert():
        conn = pymysql.connect(host=HOST,
                               port=PORT,
                               user=USER,
                               passwd=PASSWORD,
                               charset=CHARSET,
                               db=DB_NAME)
        cursor = conn.cursor()
        try:
            sql = 'INSERT INTO t_addr(PROVICE, CITY, COUNTY, DEATIL, USERID) VALUES (%s,%s,%s,%s,%s)'
            li = []
            for i in range(50):
                li.append(('湖北省', '武汉市', '高新区' + str(i), '智慧园', 6))
            # 开启事物
            conn.begin()
            cursor.executemany(sql, li)
            # 提交
            conn.commit()
        except Exception as e:
            conn.rollback()
            print(e)
            # 报错事务回滚
        finally:
            # 关闭连接
            cursor.close()
            conn.close()
    

猜你喜欢

转载自blog.csdn.net/qq_38953577/article/details/93735756