python sqlite3 工具函数

起因, 目的:

sqlite3 最常用的函数。

比如,某人给了一个 database.db 文件。 但是你登录的时候,不知道账号密码。

此文件就是,查看这个数据库的详细内容。

  1. 有哪些表
  2. 某个表的全部内容。
  3. 添加数据
代码, 见注释
python 复制代码
import os
import time
import sqlite3

# sqlite3。添加。保存。
class DB:

    def __init__(self, db_name=None, table_name=None):
        # 如果不提供数据库名称,则自动创建一个。
        dt = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
        if not db_name:
            self.db_name = f"temp_db_{dt}.db"
        else:
            self.db_name = db_name

        if not table_name:
            self.table_name = f"temp_table_{dt}"
        else:
            self.table_name = table_name

    # 查看全部的 table
    def get_tables(self):
        con = sqlite3.connect(self.db_name)
        c = con.cursor()
        sql = """SELECT name FROM sqlite_master WHERE type='table';"""
        c.execute(sql)
        tables = list(map(lambda i: i[0], c.fetchall()))
        print("All tables: ", tables)
        con.close()
        return tables

    # 查看某个 table 的全部列名
    def get_columns(self, tb_name=None):
        if not tb_name:
            tb_name = self.table_name

        con = sqlite3.connect(self.db_name)
        c = con.cursor()
        sql = f"SELECT * FROM {tb_name}"
        data = c.execute(sql)
        cols = list(map(lambda i: i[0], data.description))
        print("All columns: ", cols)
        con.close()
        return cols

    def add_many(self):
        con = sqlite3.connect(self.db_name)
        c = con.cursor()

        # 表头. 只能创建一次。
        cols = self.get_columns()
        if len(cols) == 0:
            # cols = ("比赛名", "球队名", "比赛时间", "进球数", "红牌")
            c.execute(f'''CREATE TABLE {self.table_name}
                        (game_name text, team_name text, date_time text, score text, price red_card)''')

        # 插入数据。  插入大量的数据。
        purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
                     ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
                     ('2006-04-06', 'SELL', 'A', 500, 53.00),
                     ('2006-04-06', 'EEE', 'V', 5412, 53.00),
                     ('2006-04-06', 'QQ', 'TT', 500, 53.00),
                     ]
        c.executemany('INSERT INTO fake_data VALUES (?,?,?,?,?)', purchases)
        con.commit()
        con.close()

    def show_table(self, tb_name=None):
        if not tb_name:
            tb_name = self.table_name

        con = sqlite3.connect(self.db_name)
        c = con.cursor()
        c.execute(f'SELECT * FROM {tb_name}')
        print("All data: ", c.fetchall())  # 查询全部的数据。
        info = c.fetchall()
        c.close()
        return info

if __name__ == '__main__':
    x = DB(db_name="gc3.db")
    tbs = x.get_tables()

    # x.get_columns()
    # x.show_table()
    # print()

    # x.add_many()
    # x.show_table()

结论 + todo

简单,但是常用,写篇文章,方便自己下次查看。


老哥留步,支持一下。

相关推荐
这个DBA有点耶2 小时前
同城双活落地的三座山:网络延迟、脑裂预防、反向同步
数据库·架构·dba
青春之我_XP2 小时前
MySQL 常用日期函数 实战指南
数据库·sql·mysql·数据分析·数据库开发·日期函数
Nturmoils2 小时前
sys_dump 备了库,角色和权限别漏在外面
数据库
接着奏乐接着舞。2 小时前
【2026】73道Redis 常见面试题与参考答案
数据库·redis·后端·缓存
谢白羽3 小时前
SGLang的AWQ量化笔记
笔记·python·sglang
迷迭香yy3 小时前
基金档案数据工程实战从收入分析到持仓穿透的Python解析 IG50免费开源股票数据API接口
开发语言·python
其实防守也摸鱼3 小时前
权限提升与横向移动:从内网渗透到域控的完整技术图谱
运维·服务器·数据库·安全·github·copilot·渗透
清水白石0083 小时前
Python 类型设计深度解析:TypedDict 能否替代 dataclass?从 JSON 数据边界到 API 设计的最佳实践
java·python·json
人生百态,人生如梦4 小时前
每日论文解读(9.1)——ReToolSQL:面向鲁棒Text-to-SQL的Agentic强化学习与工具增强两阶段训练框架
数据库·sql