Python SQLite中的多个唯一列

Python SQLite中的多个唯一列,python,sql,sqlite,unique-key,Python,Sql,Sqlite,Unique Key,我试图创建一个表,我需要它不允许3个字段相同的行 当我使用SQLLite在Python中创建表时,我使用了以下命令,但几乎没有得到任何结果。它通常在写了两条记录后停止,所以显然有人相信它是重复的 CREATE TABLE CorpWalletJournal ( date INT, refID INT, refTypeID INT, ownerName1 TEXT, ownerID1 INT, ownerName2 TEXT, o

我试图创建一个表,我需要它不允许3个字段相同的行

当我使用SQLLite在Python中创建表时,我使用了以下命令,但几乎没有得到任何结果。它通常在写了两条记录后停止,所以显然有人相信它是重复的

CREATE TABLE CorpWalletJournal (
    date INT, 
    refID INT, 
    refTypeID INT, 
    ownerName1 TEXT, 
    ownerID1 INT, 
    ownerName2 TEXT, 
    ownerID2 INT, 
    argName1 TEXT, 
    argID1 ID, 
    amount INT, 
    balance INT, 
    reason TEXT, 
    accountKey INT, 

    UNIQUE (ownerID1, ownerID2, accountKey, argID1)
);
因此,我希望数据库不允许ownerID1、ownerID2、accountKey和argID1相同的记录

有人能帮我吗


谢谢大家!

我不确定是什么问题。它在这里工作得很好:

import sqlite3

# connect to memory-only database for testing
con = sqlite3.connect('')
cur = con.cursor()

# create the table
cur.execute('''
CREATE TABLE CorpWalletJournal (
    date INT, refID INT, refTypeID INT, ownerName1 TEXT, 
    ownerID1 INT, ownerName2 TEXT, ownerID2 INT, argName1 TEXT, 
    argID1 ID, amount INT, balance INT, reason TEXT, accountKey INT, 
    UNIQUE (ownerID1, ownerID2, accountKey, argID1)
);
''')
con.commit()

insert_sql = '''INSERT INTO CorpWalletJournal 
(date, refID, refTypeID, ownerName1, ownerID1, ownerName2, ownerID2, 
argName1, argID1, amount, balance, reason, accountKey)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'''

## create 5 rows changing only argID1 - it works:
for argid in xrange(5): 
    cur.execute(insert_sql, (1, 1, 1, 'a', 1, 'a', 1, 'a', argid, 1, 1, 'a', 1))
con.commit()

# now try to insert a row that is already there:
cur.execute(insert_sql,  (1, 1, 1, 'a', 1, 'a', 1, 'a', 0, 1, 1, 'a', 1))
我从最后一行得到的错误是:

Traceback (most recent call last):
  File "teststdio.py", line 41, in <module>
    cur.execute(insert_sql,  (1, 1, 1, 'a', 1, 'a', 1, 'a', 0, 1, 1, 'a', 1))
sqlite3.IntegrityError: columns ownerID1, ownerID2, accountKey, argID1 
    are not unique
回溯(最近一次呼叫最后一次):
文件“teststdio.py”,第41行,在
当前执行(插入sql,(1,1,1,'a',1,'a',1,'a',0,1,1,'a',1))
sqlite3.IntegrityError:列ownerID1、ownerID2、accountKey、argID1
它们不是独一无二的

您要查找的不是唯一的,而是主键。设置主键(ownerID1、ownerID2、accountKey、argID1)时,这4个值一起就是行索引。 这意味着,如果您用这4个值编写一个新行,它将覆盖该行。因此,4个值的每个组合只能存在一次


另一方面,唯一性意味着4个值中的每个值只能使用一次。

它通常在写入2条记录后停止,因此显然有人相信它是重复的。-为什么这是显而易见的?当插入失败时,您会收到什么错误消息?您没有在任何列上指定
notnull
,因此可能会得到违反唯一约束的NULL值。插入失败后,数据是什么样子的?