有没有办法从蟒蛇内获得数据库的模式?(Is there a way to get a schema

2019-06-27 03:35发布

我试图找出一种方法来找到表的名称在数据库中(如果有的话)。 我发现,从sqlite的CLI我可以使用:

>.tables

那么对于字段:

>PRAGMA TABLE_INFO(table_name)

这显然不蟒蛇内工作。 有没有连的方式与Python做到这一点还是我应该只是使用SQLite的命令行?

Answer 1:

您应该能够访问从表名sqlite_master表。

SELECT name FROM sqlite_master WHERE type='table';

列的名称是不能直接访问。 让他们最简单的方法是查询表,从查询结果中得到的列名。

SELECT * FROM table_name LIMIT 1;


Answer 2:

从sqlite的常见问题 :

从C / C ++程序(或使用Tcl /红宝石/的Perl / Python绑定的脚本),你可以通过做一个可以访问表和索引的名字中SELECT名为“SQLITE_MASTER”一个特殊的表。 每个SQLite数据库有一个SQLITE_MASTER定义架构的数据库表。 该SQLITE_MASTER表看起来像这样:

 CREATE TABLE sqlite_master ( type TEXT, name TEXT, tbl_name TEXT, rootpage INTEGER, sql TEXT ); 

因此,要获得所有的表名执行的列表:

SELECT name FROM sqlite_master
WHERE type='table'
ORDER BY name;

要获得列名称为给定的表,使用pragma table_info命令 :

这编译返回的指定表中的每一列一行。 结果集中列包括列名,数据类型,列是否可以为NULL,并且该列的默认值。

此命令的工作就好了蟒蛇:

>>> import sqlite3
>>> conn = sqlite3.connect(':mem:')
>>> for row in conn.execute("pragma table_info('sqlite_master')").fetchall():
...     print row
... 
(0, u'type', u'text', 0, None, 0)
(1, u'name', u'text', 0, None, 0)
(2, u'tbl_name', u'text', 0, None, 0)
(3, u'rootpage', u'integer', 0, None, 0)
(4, u'sql', u'text', 0, None, 0)

不幸的是pragma语句不带参数的工作; 你必须手动插入表名(确保它不是来自不受信任来源采购和正确转义)。



Answer 3:

这是我写的基于的Martijn的响应方便的打印机:

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 "",
            ))


Answer 4:

要获得字段名,使用cur.description查询后:

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]


Answer 5:

使用SQLite行对象。 行对象具有键(),这将使你的架构。

从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']


Answer 6:

我只是想

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

汤姆·科尔的答案,并检索附加的数据库上的信息的尝试结合起来。 起初,它没有工作。 事实证明,我首先要这样附加其他数据库:

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

否则数据库将无法获得附加的数据库的读锁sqlite_master (和所有的查询将与零个结果成功)。 万一有人就在暗示别人绊倒在问题的一部分。



Answer 7:

要获取架构信息,恕我直言,下面也可以工作:

select sql from sqlite_master where type='table';


Answer 8:

结果集有一个说明,你可以得到一些信息。 它揭示了像列名和列数的一些基本的元数据。

>>> 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))


文章来源: Is there a way to get a schema of a database from within python?