有没有办法在SQLite中获取表的约束?

fra*_*ran 15 sqlite constraints list pragma

命令"pragma table_info('tablename')"列出列信息,"pragma foreign_key_list('tablename')"列出外键.如何显示表的其他约束(检查,唯一)?只解析表"sqlite_master"的字段"sql"?

jft*_*uga 9

我认为唯一的方法是这样做是你建议的方式,解析sqlite_master数据库的sql列.

Python代码执行此操作:

import sqlite3

con = sqlite3.connect("example.sqlite3")
cur = con.cursor()
cur.execute("select sql from sqlite_master where type='table' and name='example_table'")
schema = cur.fetchone()
con.close()

entries = [ tmp.strip() for tmp in schema[0].splitlines() if tmp.find("constraint")>=0 or tmp.find("unique")>=0 ]
for i in entries: print(i)
Run Code Online (Sandbox Code Playgroud)


Nab*_*bab 5

还有 pragma index_list('tablename')

http://sqlite.org/pragma.html#pragma_index_list

  • 并非所有索引都是约束,也并非所有约束都是索引。 (15认同)