SQLi中的多个唯一列

2024-09-28 22:23:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图创建一个表,在那里我需要它不允许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相同的记录。

有人能帮我吗?

谢谢你!


Tags: text命令datecreate记录tableintsqllite
2条回答

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

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

我不知道是什么问题。在这里工作得很好:

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

相关问题 更多 >