• Python3之数据库编程


    使用pymysql模块,主要用于Python3.x 连接 Mysql 数据库

    请使用pip3 install pymysql安装模块

    一、数据库连接对象

    pymysql.connect(host='', user='', password='', database='', port=0, db='', charset='')
    连接数据库
    
    db连接.begin
    开启事务
    
    db连接.close()
    关闭连接
    
    db连接.commit()
    提交事务到数据库,不提交事务所有操作都不会生效
    
    db连接.cursor()
    得到一个可以执行SQL语句并且将结果作为字典返回的游标对象
    
    db连接.rollback()
    发生错误时回滚事务
    
    db连接.select_db(db)
    选择数据库
    
    db连接.show_warnings()
    向mysql发送 "SHOW WARNINGS" 命令
    
    db连接.ping(reconnect=True)
    检查连接是否存活,连接不存在会重新发起连接

    二、游标对象

    cursor.close()
    关闭游标
    
    cursor.execute(SQL, args)
    执行单条SQL命令,返回受影响的行数
    args: 元组,列表,字典类型,为SQL命令传入的参数
    
    executemany(SQL, args)
    执行多条SQL语句,返回受影响的行数
    args: 为SQL命令传入的参数,二维多元元组或列表,多条SQL语句参数组成的元组或列表,每条SQL语句的参数也是一个元组或列表类型
    
    cursor.fetchone()
    返回最近一条SQL查询语句结果的下一行数据组成的列表或元组
    
    cursor.fetchmany(size)
    返回最近一条SQL查询语句结果的下size行数据组成的二维多元列表或元组,每行数据也是一个元组或列表
    
    cursor.fetchall()
    返回最近一条SQL查询语句结果剩下的所有行数据组成的二维多元列表或元组,每行数据也是一个元组或列表
    
    cursor.rowcount
    返回最近一条SQL语句(包括增删改查)影响的总行数

    三、示例

    1 try...except...finally... 操作数据库

    import pymysql
    
    #连接数据库
    db = pymysql.connect(host='localhost',
                        port=3306,
                        user='root',
                        password='Admin!123',
                        database='test_1',
                        charset='utf8')
    
    try:  
        cur = db.cursor()
        #查询当前数据库的版本
        cur.execute('select version();')
        print('Data version:',cur.fetchone())
            
        #sql语句
        sql_drop_table= 'drop table if exists user_info'
        sql_create_table = 'create table if not exists user_info(
                id int not null auto_increment,
                username varchar(100) not null,
                age int not null,
                password varchar(256) not null,
                sex varchar(10) not null,
                primary key(id))
                engine=Innodb DEFAULT CHARSET=utf8;'
    
        sql_insert = 'insert into user_info values(%s, %s, %s, %s, %s);'
        sql_query = 'select * from user_info where age=%s or sex=%s;'
    
        insert_arg = [1, 'Charles', 25, 'Charles!123', 'male']
        insert_args = ((2, 'Mark', 24, 'Mark!123', 'male'),
                    (3, 'Linda', 23, 'Linda!123', 'female'),
                    (4, 'Lily', 23, 'Lily!123', 'female'),
                    (5, 'Helen', 23, 'Helen!123', 'female'),
                    (6, 'Fred', 25, 'Fred!123', 'male'),
                    (7, 'Diana', 24, 'Diana!123', 'female'))
        query_arg = (23, 'female')
    
        #执行sql语句
        cur.execute(sql_drop_table)
        cur.execute(sql_create_table)
        cur.execute(sql_insert, insert_arg)
        cur.executemany(sql_insert, insert_args)
        cur.execute(sql_query, query_arg)
        #返回查询结果的下一行数据
        print(cur.fetchone())
        #返回查询结果的下两行数据(除去上一行数据)
        print(cur.fetchmany(2))
        #返回查询结果剩余的数据
        print(cur.fetchall())
        #返回查询结果数据总行数
        print(cur.rowcount)
    
        #提交    
        db.commit()
        
    except Exception as e:
        print(e.args)
        db.rollback()
    
    finally:
        #关闭游标
        cur.close()
        #关闭数据库连接
        db.close()

    2 with上下文管理

    自动回滚事务的上下文管理器:发生异常时,事务将自动回滚;否则,需要手动提交,和关闭mysql 连接对象

    import pymysql
    
    #连接数据库
    db = pymysql.connect(host='localhost',
                        port=3306,
                        user='root',
                        password='Admin!123',
                        database='test_1',
                        charset='utf8')
    
    with db.cursor() as cur:
        #查询当前数据库的版本
        cur.execute('select version();')
        print('Data version:',cur.fetchone())
            
        #sql语句
        sql_drop_table= 'drop table if exists user_info'
        sql_create_table = 'create table if not exists user_info(
                id int not null auto_increment,
                username varchar(100) not null,
                age int not null,
                password varchar(256) not null,
                sex varchar(10) not null,
                primary key(id))
                engine=Innodb DEFAULT CHARSET=utf8;'
    
        sql_insert = 'insert into user_info values(%s, %s, %s, %s, %s);'
        sql_query = 'select * from user_info where age=%s or sex=%s;'
    
        insert_arg = [1, 'Charles', 25, 'Charles!123', 'male']
        insert_args = ((2, 'Mark', 24, 'Mark!123', 'male'),
                (3, 'Linda', 23, 'Linda!123', 'female'),
                (4, 'Lily', 23, 'Lily!123', 'female'),
                (5, 'Helen', 23, 'Helen!123', 'female'),
                (6, 'Fred', 25, 'Fred!123', 'male'),
                (7, 'Diana', 24, 'Diana!123', 'female'))
        query_arg = (23, 'female')
        
        #执行sql语句
        cur.execute(sql_drop_table)
        cur.execute(sql_create_table)
        cur.execute(sql_insert, insert_arg)
        cur.executemany(sql_insert, insert_args)
        cur.execute(sql_query, query_arg)
        print(cur.fetchone())
        print(cur.fetchmany(2))
        print(cur.fetchall())
        print(cur.rowcount)
    
    #提交
    db.commit()
    #关闭数据库连接
    db.close()
  • 相关阅读:
    GitBook基本使用
    Window 远程桌面漏洞风险,各个厂家的扫描修复方案(CVE-2019-0708)
    应急响应实战笔记(续)
    不同系统下,复制文件时新文件的日期区别
    Window应急响应(六):NesMiner挖矿病毒
    利用python输出000至999中间的数
    揭秘骗局:这是一张会变的图片
    如何查看github排行热度
    zabbix使用自动发现功能批量监控服务器端口的可用性
    使用python脚本批量设置nginx站点的rewrite规则
  • 原文地址:https://www.cnblogs.com/gudanaimei/p/14401902.html
Copyright © 2020-2023  润新知