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



使用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

要确定主键是否自动递增,可以执行以下两种操作之一:
  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,)
    
  2. 如果插入了数据,表名将出现在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,)
    

最新更新