数据库-python SQLite3

数据库-python SQLite3

  • [一:sqlite3 简介](#一:sqlite3 简介)
  • [二: sqlite3 流程](#二: sqlite3 流程)
    • [1> demo](#1> demo)
    • [2> sqlite3 流程](#2> sqlite3 流程)
  • [三:sqlite3 step](#三:sqlite3 step)
    • [1> create table](#1> create table)
    • [2> insert into](#2> insert into)
    • [3> update](#3> update)
    • [4> select](#4> select)
      • [1. fetchall()](#1. fetchall())
      • [2. fetchone()](#2. fetchone())
      • [3. fetchmany()](#3. fetchmany())
    • [5> delete](#5> delete)
    • [6> other step](#6> other step)
  • [四: Mysql](#四: Mysql)
    • [1> Mysql知识详解](#1> Mysql知识详解)

一:sqlite3 简介

sqlite3 是一个内置的Python模块,可以通过Python的标准库轻松地使用,无需进行额外安装和配置。sqlite3 支持SQL语句,对数据库的操作简单高效。因此,sqlite3 非常适用于小型项目和单机应用程序,是Python开发中常用的数据库解决方案之一,能为程序提供完整的数据库解决方案.

二: sqlite3 流程

1> demo

utils_sqlite3.py

复制代码
import sqlite3
import logging
logger = logging.getLogger("utils_sqlite3")

def excute_sql(sql_connect, sql_cmd):
    sql_cursor = sql_connect.cursor()
    # logging.info(sql_cmd)
    try:
        sql_cursor.execute(sql_cmd)
        sql_connect.commit()
        sql_cursor.close()
    except Exception as e:
        logger.error(f"sqlite3.OperationalError: {e}")
        raise Exception(f"sqlite3.OperationalError: {e}")

create_tables.py

复制代码
def init_sqlite(file_name, tabel_name, primary_key):
    db_connect = sqlite3.connect(file_name)
    if primary_key:
        create_table_cmd = '''
            CREATE TABLE {}(
                ENTRY TEXT,
                PART TEXT,
                PART_LAYER TEXT,
                CASE_NAME TEXT,
                API_CONNECT TEXT,
                API_PARAMETER TEXT,
                PRIMARY KEY(ENTRY, CASE_NAME))'''.format(tabel_name)
    else:
        create_table_cmd = '''
            CREATE TABLE {}(
                ENTRY TEXT,
                PART TEXT,
                PART_LAYER TEXT,
                CASE_NAME TEXT,
                API_CONNECT TEXT,
                API_PARAMETER TEXT,)'''.format(tabel_name)
    excute_sql(db_connect, create_table_cmd)
    db_connect.close()
init_sqlite(performence_log_file, db_table_name, primary_key)

2> sqlite3 流程

step 流程
创建和连接数据库 import sqlite3 db_connect = sqlite3.connect(file_name)
创建表格并提交 sql_cursor = db_connect .cursor() db_connect.commit() sql_cursor.execute(create_table_cmd)
插入数据并提交 sql_cursor.execute(insert_sql ) db_connect.commit()
关闭连接 sql_cursor.close() db_connect.close()

三:sqlite3 step

1> create table

复制代码
import sqlite3
db_connect = sqlite3.connect(file_name)
sql_cursor = sql_connect.cursor()
create_table_cmd = '''
            CREATE TABLE {}(
                ENTRY TEXT,
                PART TEXT,
                PART_LAYER TEXT,
                CASE_NAME TEXT,
                API_CONNECT TEXT,
                API_PARAMETER TEXT,
                PRIMARY KEY(ENTRY, CASE_NAME))'''.format(tabel_name)
sql_cursor.execute(create_table_cmd)
sql_connect.commit()
 sql_cursor.close()

2> insert into

复制代码
import sqlite3
db_connect = sqlite3.connect(file_name)
sql_cursor = sql_connect.cursor()
insert_sql = '''INSERT INTO {}     		   	(ENTRY,PART,PART_LAYER,CASE_NAME,API_CONNECT,API_PARAMETER)
     VALUES ('{}', '{}', '{}', '{}', '{}', '{}')'''.format(
        db_table_name, args.entry,  args.part, args.part_layer, args.case, connect_res, "NULL")
sql_cursor.execute(insert_sql )
sql_connect.commit()
 sql_cursor.close()

3> update

复制代码
import sqlite3
db_connect = sqlite3.connect(file_name)
sql_cursor = sql_connect.cursor()
insert_sql = '''update {} set  API_PARAMETER="{}"'''.format(db_table_name, para_res)
sql_cursor.execute(insert_sql )
sql_connect.commit()
 sql_cursor.close()

4> select

1. fetchall()

fetchall()函数是游标对象(Cursor)的一个方法,用于获取查询结果集中的所有行。使用该函数,可以一次性获取查询结果集中的所有行,并以列表的形式返回。

复制代码
import sqlite3
table_name = "interface_test"
db = sqlite3.connect(path)
cursor = db.cursor()
select_sql = '''select* from {} where ENTRY = "{}"'''.format(table_name, "interface")
record_cursor = cursor.execute(select_sql)
records = record_cursor.fetchall()
db.commit()
cursor.close()
db.close()

注意:如果查询结果集非常大,使用fetchall()函数可能会消耗较多的内存。在这种情况下,可以考虑使用 fetchone()或fetchmany()函数来分批获取查询结果

2. fetchone()

fetchone()函数是游标对象(Cursor)的一个方法,用于获取查询结果集中的下一行。使用该函数,可以逐行获取查询结果集中的数据。每次调用fetchone()函数,它会返回结果集中的下一行数据。当没有更多的行可用时,它将返回None。

复制代码
table_name = "interface_test"
db = sqlite3.connect(path)
cursor = db.cursor()
select_sql = '''select* from {} where ENTRY = "{}"'''.format(table_name, "interface")
record_cursor = cursor.execute(select_sql)
#获取结果中下一行数据
records = record_cursor.fetchone()
db.commit()
cursor.close()
db.close()

3. fetchmany()

fetchmany(size)函数是游标对象(Cursor)的一个方法,用于获取查询结果集中的多行数据,最多获取size行。注意:每次调用 fetchmany()都会从上次获取数据的地方开始继续获取,也就是说,如果先调用了fetchmany(5),然后再调用 fetchmany(5),那么第二次调用将返回查询结果的第6-10行。如果想要重新从头开始获取数据,需要先调用 cursor.scroll(0, mode='absolute') 来重置游标位置。

复制代码
table_name = "interface_test"
db = sqlite3.connect(path)
cursor = db.cursor()
select_sql = '''select* from {} where ENTRY = "{}"'''.format(table_name, "interface")
record_cursor = cursor.execute(select_sql)
#最多获取5行
records = record_cursor.fetchmany(5)
db.commit()
cursor.close()
db.close()

5> delete

复制代码
import sqlite3
table_name = "interface_test"
db = sqlite3.connect(path)
cursor = db.cursor()
delete_sql = '''delete from {} where ENTRY = "{}"'''.format(table_name, "interface")
record_cursor = cursor.execute(delete_sql)
db.commit()
cursor.close()
db.close()

6> other step

step detail
ALTER TABLE 修改表格结构
DROP TABLE 删除表格
CREATE INDEX 创建索引
DROP INDEX 删除索引
SELECT DISTINCT 选择唯一记录
ORDER BY 排序查询结果
GROUP BY 按列分组
HAVING 过滤分组后的数据
LIMIT- 限制查询结果数量
JOIN 连接表格
LEFT JOIN 左连接
RIGHT JOIN 右连接
FULL OUTER JOIN 全外连接
UNION 合并两个查询结果
EXCEPT 排除两个查询结果中的重复行

四: Mysql

1> Mysql知识详解

https://blog.csdn.net/weixin_42914706/article/details/111658640

相关推荐
asdfg12589631 分钟前
一文通俗理解JDBC中的核心概念+案例
java·数据库·oracle·jdbc
AI行业学习4 分钟前
CC‑Switch v3.16.1-下载、配置、安装(2026‑06‑01 最新官方版)
开发语言·人工智能·windows·python
unity工具人5 分钟前
python+yolov8 图像识别-测试案例
python·opencv·yolo
lipku6 分钟前
LiveTalking 更新:集成 vLLM-Omni TTS服务
python·开源·数字人·vllm·实时数字人
点灯小铭8 分钟前
基于单片机与DAC0832的双路波形信号发生系统设计
数据库·单片机·mongodb·毕业设计·课程设计·期末大作业
其实防守也摸鱼10 分钟前
Claude 大模型新手入门与实战指南
人工智能·python·功能测试·ai·大模型·测评
Dust-Chasing13 分钟前
Claude Code源码剖析 - 权限系统
人工智能·python·ai
小陈phd13 分钟前
Text2SQL智能体学习笔记(二)——NL2SQL落地的隐形基石:元数据库
数据库·笔记·学习
霸道流氓气质14 分钟前
阿里云 OSS 从零到实战:概念、配置与 Spring Boot 集成指南
数据库·spring boot·阿里云
茉莉玫瑰花茶15 分钟前
综合案例 - AI 智能租房助手 [ 4 ]
数据库·python·ai·langgraph