如何以编程方式确定SQLite中的列是否设置为AUTOINCREMENT?

时间:2013-05-23 21:43:42

标签: python database sqlite

使用Python 2.7的sqlite3库,如何确定表的哪些列为AUTOINCREMENT?我知道我可以使用SQLite命令行实用程序,但我该如何以编程方式执行。我轻率地查看了SQLite文档,我能找到的最近的PRAGMA命令是table_info

1 个答案:

答案 0 :(得分:6)

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

要确定主键是否自动增量 ,您可以执行以下两项操作之一:

  1. 查询sqlite_master table并检查架构中是否提及AUTOINCREMENT

    >>> c.execute('SELECT 1 FROM sqlite_master WHERE tbl_name="foo" AND sql LIKE "%AUTOINCREMENT%"')
    <sqlite3.Cursor object at 0x10a124ef8>
    >>> c.fetchone()
    (1,)
    
  2. 如果您已插入数据,表名将显示在sqlite_sequence table

    >>> 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,)