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

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


老哥留步,支持一下。

相关推荐
--fancy18 小时前
股票预测情感分析研究案例分析
python
shughui18 小时前
PyCharm 完整教程(旧版本卸载+旧/新版本下载安装+基础使用,2026最新版附安装包)
ide·python·pycharm
NCIN EXPE18 小时前
redis 使用
数据库·redis·缓存
MongoDB 数据平台18 小时前
为编码代理引入 MongoDB 代理技能和插件
数据库·mongodb
极客on之路19 小时前
mysql explain type 各个字段解释
数据库·mysql
代码雕刻家19 小时前
MySQL与SQL Server的基本指令
数据库·mysql·sqlserver
lThE ANDE19 小时前
开启mysql的binlog日志
数据库·mysql
小糖学代码19 小时前
LLM系列:1.python入门:15.JSON 数据处理与操作
开发语言·python·json·aigc
yejqvow1219 小时前
CSS如何控制placeholder文字的颜色_使用--placeholder伪元素
jvm·数据库·python
oLLI PILO19 小时前
nacos2.3.0 接入pgsql或其他数据库
数据库