python sqlite 获取表名、表

2020-01-09 15:35:41 浏览数 (1)

代码语言:javascript复制
# -*- coding: UTF-8 -*-
import sqlite3
import pprint

def sqlite_read():
    """python读取sqlite数据库文件
    """
    mydb = sqlite3.connect('data.sqlite')       # 链接数据库
    cur = mydb.cursor()                         # 创建游标cur来执行SQL语句

    # 获取表名
    cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
    Tables = cur.fetchall()                     # Tables 为元组列表
    print Tables

    tbl_name = Tables[0][0]                     # 获取第一个表名

    # 获取表的列名
    cur.execute("SELECT * FROM {}".format(tbl_name))
    col_name_list = [tuple[0] for tuple in cur.description]
    pprint.pprint(col_name_list)

    # 获取表结构的所有信息
    cur.execute("PRAGMA table_info({})".format(tbl_name))
    pprint.pprint(cur.fetchall())

0 人点赞