我正在尝试找出一种方法来查找数据库中的表名(如果存在的话)。我发现可以从 sqlite cli 中使用:
>.tables
然后对于字段:
>PRAGMA TABLE_INFO(table_name)
这显然在 python 中不起作用。有没有办法用 python 做到这一点,还是我应该只使用 sqlite 命令行?
最佳答案
来自 sqlite FAQ :
From within a C/C++ program (or a script using Tcl/Ruby/Perl/Python bindings) you can get access to table and index names by doing a
SELECT
on a special table named "SQLITE_MASTER". Every SQLite database has anSQLITE_MASTER
table that defines the schema for the database. TheSQLITE_MASTER
table looks like this: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
command :
This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column.
这个命令在 python 中工作得很好:
>>> 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
语句不适用于参数;您必须手动插入表名(确保它不是来自不受信任的来源并正确转义)。
关于python - 有没有办法从 python 中获取数据库的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11996394/