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

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


老哥留步,支持一下。

相关推荐
Yan-英杰10 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
weixin_307779131 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
小喵要摸鱼6 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
IT古董6 小时前
【开源向量数据库】Milvus简介
数据库·开源·milvus
bdawn6 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML6 小时前
Python数据可视化简介
开发语言·python·数据可视化
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
web150850966416 小时前
SQL 建表语句详解
java·数据库·sql