zoukankan      html  css  js  c++  java
  • Python 使用数据库(SQLite)

    SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。

    Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。

    在使用SQLite前,我们先要搞清楚几个概念:

    表是数据库中存放关系数据的集合,一个数据库里面通常都包含多个表,比如学生的表,班级的表,学校的表,等等。表和表之间通过外键关联。

    要操作关系数据库,首先需连接到数据库,一个数据库连接称为Connection

    连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句,然后,获得执行结果。

    Python定义了一套操作数据库的API接口,任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可。

    由于SQLite的驱动内置在Python标准库中,所以我们可以直接来操作SQLite数据库

    # 导入模块
    import sqlite3
    
    # ##### 使用数据库前
    # 数据库文件路径
    db_path = r'D:\test.db' # 物理(磁盘)存储(raw 字符串)
    # 创建数据库连接
    conn = sqlite3.connect(db_path)
    
    def dict_factory(cursor, row):
        '''修改查询格式'''
        d = {}
        for idx, col in enumerate(cursor.description):
            d[col[0]] = row[idx]
        return d
    # conn.row_factory = dict_factory
    
    # 创建游标
    cur = conn.cursor()
    
    # ##### 数据库操作
    sql = '''
    create table if not exists tb_test(
        id integer primary key autoincrement,
        name varchar(20) not null,
        remark text
    )
    '''
    # 执行SQL语句
    cur.execute(sql)
    sql = '''
        drop table tb_test
    '''
    # cur.execute(sql)
    # ### insert
    sql = '''
    INSERT INTO tb_test(name, remark)
    VALUES('zhangsan', '学习Python')
    '''
    # cur.execute(sql)
    sql = '''
    INSERT INTO tb_test(name, remark)
    VALUES(?, ?)
    '''
    # ?, 参数格式化,避免SQL注入(安全)
    # 不要使用str.format或者字符串拼接的方式来构造SQL语句(不安全)
    stuents = [
        ('李斯', '统一文字,小篆'),
        ('唐三', '斗罗大陆'),
        ('王小二', '中国惊奇先生')
    ]
    # 插入多条数据
    # cur.executemany(sql, stuents)
    # commit, 提交更改
    conn.commit()
    
    # ### select
    sql = '''
    SELECT
        COUNT(1) AS total,
        'test' AS test
    FROM tb_test
    '''
    # 查询单个数据
    cur.execute(sql)
    result_one = cur.fetchone()
    print(result_one)
    
    sql = '''
    SELECT *
    FROM tb_test
    WHERE name = ?
    OR id < 3
    '''
    params = ('唐三',)
    # 查询单条数据
    cur.execute(sql, params)
    result_one = cur.fetchone()
    print(result_one)
    # 查询多条数据
    cur.execute(sql, params)
    page_count = 2 # 一次查询的数据条数
    result_many = cur.fetchmany(page_count)
    print(result_many)
    # 查询全部数据
    cur.execute(sql, params)
    result_all = cur.fetchall()
    print(result_all)
    """
    """
    # ### update
    # ### delete
    
    
    # ##### 使用数据库后
    # 关闭游标
    cur.close()
    # 关闭数据库连接
    conn.close()

    初次发表,请多多关照

  • 相关阅读:
    项目管理【44】 | 项目干系人管理-识别干系人
    移动端开发基础【15】H5和小程序开发注意事项
    召回率recall,IoU, mPA理解,针对video detection领域
    转:batch normalization, instance normalization, layer normalization, group normalization
    自监督(对比学习)资料
    转:非极大值抑制(Non-Maximum Suppression,NMS)
    转:Zero-shot Learning / One-shot Learning / Few-shot Learning
    转:top1错误率、top5正确率
    转:如何理解Inductive bias?
    台式机更新后没有声音了怎么办,Realtek音频管理器
  • 原文地址:https://www.cnblogs.com/cp9648/p/9379435.html
Copyright © 2011-2022 走看看