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

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

    Here's a convenient printer I wrote based Martijn's response:

    def printSchema(connection):
        for (tableName,) in connection.execute(
            """
            select NAME from SQLITE_MASTER where TYPE='table' order by NAME;
            """
        ):
            print("{}:".format(tableName))
            for (
                columnID, columnName, columnType,
                columnNotNull, columnDefault, columnPK,
            ) in connection.execute("pragma table_info('{}');".format(tableName)):
                print("  {id}: {name}({type}){null}{default}{pk}".format(
                    id=columnID,
                    name=columnName,
                    type=columnType,
                    null=" not null" if columnNotNull else "",
                    default=" [{}]".format(columnDefault) if columnDefault else "",
                    pk=" *{}".format(columnPK) if columnPK else "",
                ))
    
    0 讨论(0)
  • 2020-12-09 16:45

    result sets have a description that you can get some information from. It reveals some basic metadata like column name and number of columns.

    >>> rs = c.execute('''SELECT * FROM news WHERE 1=0''');
    >>> dir(rs)
    ['__class__', '__delattr__', '__doc__', '__format__',  
    '__getattribute__', '__hash__', '__init__', '__iter__', '__new__',  
    '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
    '__str__', '__subclasshook__', 'arraysize', 'close', 'connection',
    **'description'**, 'execute', 'executemany', 'executescript', 'fetchall',
    'fetchmany', 'fetchone', 'lastrowid', 'next', 'row_factory',
    'rowcount', 'setinputsizes', 'setoutputsize']
    
    
    
    >>> print(rs.description)
    (('id', None, None, None, None, None, None), 
    ('imageUrl', None, None, None, None, None, None), 
    ('headline', None, None, None, None, None, None), 
    ('who', None, None, None, None, None, None))
    
    0 讨论(0)
  • 2020-12-09 16:48

    Use sqlite row object. A row object has keys() that will give you the schema.

    from docs.python.org

    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    c.execute('select * from stocks')
      <sqlite3.Cursor object at 0x7f4e7dd8fa80>
    r = c.fetchone()
    type(r)
      <type 'sqlite3.Row'>
      r
      (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
    r.keys()
      ['date', 'trans', 'symbol', 'qty', 'price']
    
    0 讨论(0)
  • 2020-12-09 17:01

    You should be able access the table names from the sqlite_master table.

    SELECT name FROM sqlite_master WHERE type='table';
    

    The names of the columns are not directly accessible. The easiest way to get them is to query the table and get the column names from the query result.

    SELECT * FROM table_name LIMIT 1;
    
    0 讨论(0)
  • 2020-12-09 17:01

    I just tried

    SELECT name FROM my_db.sqlite_master WHERE type='table';
    

    to combine Tom Kerr's answer and the attempt to retrieve information on an attached database. At first it didn't work. Turns out I first have to attach the other database this way:

    ATTACH DATABASE 'file:my_other_database_file.db?cache=shared' as my_db;
    

    otherwise the database will fail to obtain a read lock for the attached database's sqlite_master (and all queries will succeed with zero results). Just a hint in case anybody else stumbles upon that part of the issue.

    0 讨论(0)
  • 2020-12-09 17:02

    To get the schema information, IMHO, below also works:

    select sql from sqlite_master where type='table';
    
    0 讨论(0)
提交回复
热议问题