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

时间:2012-03-09 14:51:41

标签: sqlite list constraints pragma

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

2 个答案:

答案 0 :(得分:8)

我认为唯一的方法就是按照你的建议,解析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)

答案 1 :(得分:3)

还有pragma index_list('tablename')

请参阅http://sqlite.org/pragma.html#pragma_index_list

相关问题