python - 有没有办法从 python 中获取数据库的模式?

标签 python sqlite database-schema

我正在尝试找出一种方法来查找数据库中的表名(如果存在的话)。我发现可以从 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 an SQLITE_MASTER table that defines the schema for the database. The SQLITE_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/

相关文章:

postgresql - 在 PostgreSQL 中使用 dblink 时如何包含模式 inf?

python - 将日期插入 DataFrame 的行中

python - libpng 警告 : interlace handling should be turned on when using png_read_image in Python/PyGame

python - 如何使用 python falcon rest api 创建具有多个用户级别的 token 的用户身份验证

python multiprocessing.Process.terminate - 如何杀死子进程

python-3.x - sqlite3.数据库错误: file is not a database

c# - SQLite 的替代品,具有保护

python - 使用 sqlite3 在 python 中删除表

mysql - 将 SHOW COLUMNS 的输出分组到逗号分隔的列表中

php - Laravel - 动态创建表(无需迁移)