• 第十三章 Python操作数据库


    系列文章目录

    第一章 Python 基础知识
    第二章 python 字符串处理
    第三章 python 数据类型
    第四章 python 运算符与流程控制
    第五章 python 文件操作
    第六章 python 函数
    第七章 python 常用内建函数
    第八章 python 类(面向对象编程)
    第九章 python 异常处理
    第十章 python 自定义模块及导入方法
    第十一章 python 常用标准库
    第十二章 python 正则表达式
    第十三章 python 操作数据库



    pymysql模块准备与基本使用

    pymysql模块

    pymysql是python中操作MySQL的模块,其使用方法和MySQLdb几乎相同,但目前pymysql支持python3.x而后者不支持3.x版本
    pymysql是第三方模块,需要单独安装,首选通过pip安装PyMySQL

    pip3 install pymysql
    
    • 1

    基本使用

    先创建库以及表

    # 创建库
    create database test;
    创建表
    use test;
    create table user(id int primary key not null auto_increment,username varchar(50) not null,password varchar(50) not null);
    查看表
    show tables;
    查看表类型
    describe user;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    from unittest import result
    import pymysql
    conn = pymysql.connect(host='127.0.0.1',
                            port=3306,
                            user='root',
                            password='123.com',
                            db='test',
                            charset='utf8',
                            cursorclass=pymysql.cursors.DictCursor
                            )
    # 创建游标
    cursor = conn.cursor()
    # 向user表插入数据id是自增不需要插入
    sql = "insert into user(username,password) values('root','123.com')"
    cursor.execute(sql)
    # 向数据库提交,进行写入
    conn.commit()
    sql = "select * from user"
    cursor.execute(sql)
    result = cursor.fetchone()
    print(result)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在这里插入图片描述

    connect()函数常用参数

    方法描述
    host数据库主机地址
    user数据库账户
    passwd账户密码
    db使用的数据库
    port数据库主机端口,默认3306
    connect_timeout连接超时时间,默认10,单位秒
    charset使用的字符集
    cursorclass自定义游标使用的类,上面实例用的是字典类,以字典形式返回结果,默认是元组形式

    连接对象常用方法

    方法描述
    commit()提交事务,对支持事务的数据库和表,如果提交修改操作,不适用这个方法,则不会写到数据库中
    rollback()失误回滚,对支持事务的数据库和表,如果执行此方法,则回滚当前事务,在没有commit()前提下
    cursor([cursorclass])创建一个游标对象,所有的sql语句的执行都要再游标对象下进行,mysql本身不支持游标,mysqldb模块对其游标进行了方针

    游标对象常用方法

    方法描述
    close()关闭游标
    excute(sql)执行sql语句
    executemany(sql)执行多条sql语句
    fetchone()从运行结果中取第一条记录,返回字典
    fetchmany(n)从运行结果中取n条记录,返回列表
    fetchall()从运行结果中取所有记录,返回列表
    from unittest import result
    import pymysql
    conn = pymysql.connect(host='127.0.0.1',
                            port=3306,
                            user='root',
                            password='123.com',
                            db='test',
                            charset='utf8',
                            cursorclass=pymysql.cursors.DictCursor
                            )
    try:
        with conn.cursor() as cursor:
            # 创建一条记录
            sql = "insert into user(username,password) values('wang','123.com')"
            cursor.execute(sql)
        # 写入到数据库
        conn.commit()
    
        with conn.cursor() as cursor:
            # 读取一条记录
            sql = "select id,username,password from user"
            cursor.execute(sql)
            result = cursor.fetchall()
            print(result)
    finally: # 不管try有没有执行,都执行这个进行关闭数据库
        conn.close()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    数据库增删改查

    from sqlite3 import Cursor
    from unittest import result
    import pymysql
    conn = pymysql.connect(host='127.0.0.1',
                            port=3306,
                            user='root',
                            password='123.com',
                            db='test',
                            charset='utf8',
                            cursorclass=pymysql.cursors.DictCursor
                            )
    cursor = conn.cursor()
    # 增
    sql = "insert into user(username,password) values(%s,%s)"
    args = [('张三','123.com'),('李四','123.com'),('王五','123.com')]
    cursor.executemany(sql,args)
    conn.commit()
    # 删
    sql = "delete from user  where id='7'"
    cursor.execute(sql)
    conn.commit()
    # 改
    sql = "update user set password='66666'  where id='6'"
    cursor.execute(sql)
    conn.commit()
    # 查
    sql = "select * from user"
    cursor.execute(sql)
    print('获取第一条记录:',cursor.fetchone())
    print('获取指定多少条记录:',cursor.fetchmany(3))
    print('获取所有记录:',cursor.fetchall())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    在这里插入图片描述

    案例:查询数据库并格式化输出

    import pymysql
    conn = pymysql.connect(host='127.0.0.1',
                            port=3306,
                            user='root',
                            password='123.com',
                            db='test',
                            charset='utf8',
                            cursorclass=pymysql.cursors.DictCursor
                            )
    try:
        with conn.cursor() as cursor:
            # 读取一条记录
            sql = "select * from user"
            cursor.execute(sql)
            result = cursor.fetchall()
            for d in result:
                print(f"ID:{d['id']},用户名:{d['username']},密码:{d['password']}")
    finally: # 不管try有没有执行,都执行这个进行关闭数据库
        conn.close()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    总结

    以上就是今天要讲的内容,本文仅仅简单学习了python操作数据库,针对数据库做增删改查。

  • 相关阅读:
    十四天学会C++之第一天(入门和基本语法)
    【mcuclub】舵机-SG90
    第四代智能井盖传感器,实时守护井盖位安全
    List Set Map Queue Deque 之间的区别是什么?
    HostMonitor邮件告警详细解读----生产可用
    4-为什么有了gil锁还要互斥锁?进程,线程和协程 以及进程,线程和协程的使用场景、什么是鸭子类型、并行和并发
    ArrayList和LinkList区别
    【学习笔记】开源计算机视觉库OPENCV学习方案
    Bash脚本自学 - 输入输出重定向
    postgresql字符串处理的函数
  • 原文地址:https://blog.csdn.net/weixin_42434700/article/details/134255429