ZhangZhihui's Blog  
import sqlite3

from apps.app.env_settings import MAS_DB

con = sqlite3.connect(MAS_DB)


def list_tables(p=False):
    cursor = con.cursor()
    tables_list = cursor.execute('SELECT name FROM sqlite_master WHERE type="table"').fetchall()
    tables = [tup[0] for tup in tables_list if tup[0].split('_')[0] != 'sqlite']
    if p is True:
        for table in tables:
            print(table)
    return tables


def list_columns(table_name, p=False):
    cursor = con.cursor()
    cursor.execute(f'SELECT * FROM { table_name }')
    columns = [tup[0] for tup in cursor.description]
    if p is True:
        print(table_name + ':')
        for col in columns:
            print('    ' + col)
    return columns


def print_all_tables_columns():
    _ = [list_columns(t, p=True) for t in list_tables()]


def run_select_sql(sql, p=False):
    cursor = con.cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    if p is True:
        columns = [tup[0] for tup in cursor.description]
        print('\t|\t'.join(columns))
        for row in rows:
            row_str = [str(col) for col in row]
            print('\t|\t'.join(row_str))
    return rows


def run_sql_commit(sql):
    con.execute(sql)
    con.commit()

 

posted on 2021-12-24 15:29  ZhangZhihuiAAA  阅读(87)  评论(0编辑  收藏  举报