python - SQLite 中的多个唯一列

标签 python sql sqlite unique-key

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

有人可以帮我解决这个问题吗?

谢谢!

最佳答案

我不确定问题出在哪里。它在这里工作正常:

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

关于python - SQLite 中的多个唯一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4604319/

相关文章:

python - 如何在 python 脚本中调试 KCL(python)?

android - 如何将 Shift-JIS 编码的字符串转换为 UTF-8?

c++ - SQLite3 错误无法打开数据库文件

python - 如何使用 Sphinx 链接到 str 方法?

python - Matplotlib 在刻度标签(字符串)中显示美元符号

python - 在 sklearn 中使用 Boosting 树生成特征

mysql - SQL聚合记录的运行计数

mysql - 在单个查询中显示标记和最大标记

sql - 浏览 SQL-Dump 文件而不将其导入 DBMS?

mysql - 选择在 SQL 中查找更新的列和行