Is there a way to get a schema of a database from within python?

前端 未结 10 1927
走了就别回头了
走了就别回头了 2020-12-09 16:06

I\'m trying to find out a way to find the names of tables in a database(if any exist). I find that from a sqlite cli I can use:

>.tables
<
10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 17:06

    Assuming the name of the database is my_db and the name of the table is my_table, to get the name of the columns and the datatypes:

    con = sqlite.connect(my_db)
    cur = con.cursor()
    query =  "pragma table_info({})".format(my_table)
    table_info = cur.execute(query).fetchall()
    

    It returns a list of tuples. Each tuple has the order, name of the column and data type.

提交回复
热议问题