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

前端 未结 10 1937
走了就别回头了
走了就别回头了 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:08

    To get the field names, use cur.description after the query:

    import sqlite3.dbapi2 as sqlite
    con = sqlite.connect(":memory:")
    cur = con.cursor()
    con.executescript("""
        create table test (name, address);
        insert into test (name, address) values ("Jer", "Monterey Street");
    """)
    
    cur.execute("select * from test where 1=0")
    rs = cur.fetchall()  ## will be [] because of where clause
    field_names = [r[0] for r in cur.description]
    

提交回复
热议问题