使用Python 2.7的sqlite3
库,我如何确定表的哪些列是AUTOINCREMENT
?我知道我可以使用SQLite命令行实用程序,但是我如何通过编程来实现呢?我粗略地浏览了一下SQLite文档,我能找到的最接近的PRAGMA
命令是table_info
。
AUTOINCREMENT
仅适用于主键。因此,对于给定的表,可以使用PRAGMA table_info([tablename])
来确定哪个列是主键:
>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.execute('CREATE TABLE foo (bar INTEGER PRIMARY KEY AUTOINCREMENT, baz)')
<sqlite3.Cursor object at 0x10a124f50>
>>> c = conn.cursor()
>>> c.execute('PRAGMA table_info("foo")')
<sqlite3.Cursor object at 0x10a124ef8>
>>> for row in c: print row
...
(0, u'bar', u'INTEGER', 0, None, 1)
(1, u'baz', u'', 0, None, 0)
>>> [col[0] for col in c.description]
['cid', 'name', 'type', 'notnull', 'dflt_value', 'pk']
因此,行中的最后一列是pk
行,对于bar
,设置为1
。
查询
sqlite_master
表,检查模式中是否提到AUTOINCREMENT
:>>> c.execute('SELECT 1 FROM sqlite_master WHERE tbl_name="foo" AND sql LIKE "%AUTOINCREMENT%"') <sqlite3.Cursor object at 0x10a124ef8> >>> c.fetchone() (1,)
如果插入了数据,表名将出现在
sqlite_sequence
表中:>>> c.execute('insert into foo (baz) values (1)') <sqlite3.Cursor object at 0x10a124ef8> >>> c.execute('SELECT 1 FROM sqlite_sequence WHERE name="foo"') <sqlite3.Cursor object at 0x10a124ef8> >>> c.fetchone() (1,)