1

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

当我使用 SQLLite 在 Python 中创建表时,我使用以下方法,但我几乎没有得到任何结果。它通常在写入 2 条记录后停止,因此显然有些东西认为它是重复的。

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 相同的记录。

任何人都可以帮我解决这个问题吗?

谢谢!

4

2 回答 2

2

I'm not sure what is the problem. It works fine here:

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

The error I get from last line is:

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
于 2011-01-05T13:39:59.637 回答
0

您不是在寻找 UNIQUE,而是在寻找 PRIMARY KEY。当您设置 PRIMARY KEY (ownerID1, ownerID2, accountKey, argID1) 时,这 4 个值加起来就是行索引。这意味着,如果您使用这 4 个值等于现有值写入一个新行,它将覆盖该行。因此,这 4 个值的每个组合只能存在一次。

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

于 2012-07-04T23:48:58.613 回答