Auto Increment on Composite Primary Key - Sqlite3 + Python

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I have a code like this

c.execute('CREATE TABLE IF NOT EXISTS base (ID INTEGER NOT NULL, col2 TEXT NOT NULL, col3 INTEGER, PRIMARY KEY(ID, col2))') 

This code gives me an sqlite3.IntegrityError exception even though I am very sure that I am writing the record for the first time.

So, I tried

c.execute('CREATE TABLE IF NOT EXISTS base (ID INTEGER, col2 TEXT, col3 INTEGER, PRIMARY KEY(ID, col2))') 

This inserts the row fine in the base table BUT, ID column is not auto incremented at all.

What can I do? Any idea?

回答1:

In sqlite, you only get autoincrement behavior when only one integer column is the primary key. composite keys prevent autoincrement from taking effect.

You can get a similar result by defining id as the only primary key, but then adding an additional unique constraint on id, col3.

If that's still not quite what you want (say, id's don't need to be unique at all), you probably will have to use a trigger to make autoincrement work.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!