• Python学习七:数据库编程接口


    一、数据库编程接口

    1.1 连接对象

    1.1.1 获取连接对象

    数据库连接对象主要提供获取数据库游标对象和提交、回滚事物的方法,以及关闭数据库连接

    使用connet()函数连接对象
    参数

    1. dsn:数据源名称,给出该参数标识数据库依赖
    2. user: 用户名
    3. password:用户密码
    4. host:主机名
    5. database:数据库名称
    6. charset:编码
    7. cursorclass:驱动
    8. port:端口号
    
    import pymysql
    if __name__ == '__main__':
        conn=pymysql.connect(host='127.0.0.1',
                             port=3306,
                             user='root',
                             password='root',
                             db='kc',
                             charset='utf8',
                             cursorclass=pymysql.cursors.DictCursor
                             )
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    1.1.2 连接对象的方法

    1. close():关闭数据库连接
    2. commit():提交事务
    3. rollback():回滚事务
    4. cursor():获取游标对象,操作数据库,执行DML操作、调用存储过程等

    2.1 游标对象

    游标对象代表数据库中的游标,用于指示抓取数据库操作上下文。主要提供执行sql语句,调用存储过程、获取查询结果等方法。

    使用coursor()函数连接对象

    游标对象属性

    1. description :数据库列类型和值得描述对象
    2. rowcount:放回结果的行数信息统计

    游标对象的方法

    1. callproc(procname,[,parameters]) 调用存储过程,需要数据库支持
    2. close()关闭当前游标
    3. 0excute(operation [,parameters]) 执行数据库操作,SQL语句或者数据库命令
    4. excutemany(operation,seq_of_params) 用于批量操作,如批量更新
    5. fetchone() 获取查询结果集的下一条信息
    6. fetchmany(size) 获取指定数量的记录
    7. nextset() 跳至下一个可用的结果集
    8. arraysize 使用指定fetchmany()获取行数,默认为1
    9. setinputsizes(sizes) 设置在调佣execute*()方法时分配的内存区域大小
    10. setoutputsizes(sizes)

    参考地址
    在这里插入图片描述

    
    '''
    封装一个mysql工具类(需要自己写SQL语句)
    功能:mysql数据库操作
    步骤:
        1.连接数据库
        2.通过连接对象,获取游标对象
        3.增删改查操作
    方法:
        1.查
        2.增删改 commit,rollback
    '''
    
    # 先要导入pymysql
    import pymysql
    
    # 把连接参数定义成字典
    config = {
        "host": "127.0.0.1",
        "port": 3307,
        "database": "lebo",
        "charset": "utf8",
        "user": "root",
        "passwd": "root"
    }
    
    
    class Mysqldb():
        # 初始化方法
        def __init__(self):
            # 初始化方法中调用连接数据库的方法
            self.conn = self.get_conn()
            # 调用获取游标的方法
            self.cursor = self.get_cursor()
    
        # 连接数据库的方法
        def get_conn(self):
            # **config代表不定长参数
            conn = pymysql.connect(**config)
            return conn
    
        # 获取游标
        def get_cursor(self):
            cursor = self.conn.cursor()
            return cursor
    
        # 查询sql语句返回的所有数据
        def select_all(self, sql):
            self.cursor.execute(sql)
            return self.cursor.fetchall()
    
        # 查询sql语句返回的一条数据
        def select_one(self, sql):
            self.cursor.execute(sql)
            return self.cursor.fetchone()
    
        # 查询sql语句返回的几条数据
        def select_many(self, sql, num):
            self.cursor.execute(sql)
            return self.cursor.fetchmany(num)
    
        # 增删改除了SQL语句不一样其他都是一样的,都需要提交
        def commit_data(self, sql):
            try:
                # 执行语句
                self.cursor.execute(sql)
                # 提交
                self.conn.commit()
                print("提交成功")
            except Exception as e:
                print("提交出错\n:", e)
                # 如果出错要回滚
                self.conn.rollback()
    
        # 当对象被销毁时,游标要关闭,连接也要关闭
        # 创建时是先创建连接后创建游标,关闭时是先关闭游标后关闭连接
        def __del__(self):
            self.cursor.close()
            self.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
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    
    
    # 已经封装好mysql类了,就不用导入pymsql了,直接导入封装好的类
    
    from mysql_util import Mysqldb
    
    # 实例化
    my_db = Mysqldb()
    
    # 写查询SQL语句
    sql = "select * from user where id>5"
    # 查询所有
    select_all = my_db.select_all(sql)
    print("查询所有数据:\n", select_all)
    # 查询一条
    select_one = my_db.select_one(sql)
    print("查询一条数据:\n", select_one)
    # 查询多条
    select_many = my_db.select_many(sql, 3)
    print("查询3条数据:\n", select_many)
    
    # 新增一条数据
    value = (16, 'BBQ')
    sql = f"insert into user values {value}"
    insert_one = my_db.commit_data(sql)
    # 新增多条数据
    values = "(17, 'aaa'), (18, 'bbb'), (19, 'ccc')"
    sql = f"insert into user values {values}"
    insert_many = my_db.commit_data(sql)
    
    # 修改数据
    sql = "update user set name = '出不去了' where id = 17"
    my_db.commit_data(sql)
    
    # 删除数据
    sql = "delete from user where id = 17"
    my_db.commit_data(sql)
    
    
    • 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
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
  • 相关阅读:
    反压缩 js ,我的万花筒写轮眼开了,CV 能力大幅提升
    log4net日志使用示例
    软件设计师-个人笔记-错题集
    Dubbo底层网络连接模型
    input输入路径,读取图片尺寸,移动手机截图“满屏”相同尺寸图片到别的文件夹
    python+playwright 学习-82 Request 对象
    elasticsearch 相似度计算
    业务定制型异地多活架构设计
    React--组件更新机制&组件性能优化
    解决Git报错:fatal: detected dubious ownership in repository at
  • 原文地址:https://blog.csdn.net/huiguo_/article/details/127449387