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

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

提交回复
热议问题