在SQLite中没有INSERT OR REPLACE INTO
或PRIMARY KEY
的情况下,有没有可能使用UNIQUE
的方法?
我想更新表中的值(如果不存在4个参数与之匹配的值),我想插入一个新行。但是这4个参数不是PRIMARY KEY
或UNIQUE
(可以重复,但四个是唯一的)。
我尝试使用WHERE
,但是INSERT
不允许这样做。同样,仅UPDATE
不会添加新行。
cur.execute('''INSERT OR REPLACE INTO FileNameStatus
(FileName, Delivery, SW, FuncName,
LinkModDate, ExtSrcModDate, ExtSrcModifier,
ExtAttModDate, ExtAttModifier, Error, Warning)
VALUES (?, ?, ?, ?, ? ,? ,? ,? ,? ,? ,?)
WHERE FileName = :file AND Delivery = :dvry AND SW = :sw AND FuncName = :func''',
(eachRow, {"file": eachRow[0], "dvry": eachRow[1], "sw": eachRow[2], "func": eachRow[3]},
))
是否可以使用SQLite?
答案 0 :(得分:0)
相反,您可以做的是
QUERY = "query to select the 4 fields"
cursor.execute(QUERY, params)
#if cursor row count is > 0 then you have the fields present in the database and you can update
#if it is == 0, then you know that they don't exist and you can insert
答案 1 :(得分:0)
您可以使用EXISTS
来检查值是否已经存在:
INSERT INTO FileNameStatus(FileName, Delivery, SW, FuncName,
LinkModDate, ExtSrcModDate, ExtSrcModifier,ExtAttModDate, ExtAttModifier, Error, Warning)
SELECT ?, ?, ?, ?, ? ,? ,? ,? ,? ,? ,?
WHERE NOT EXISTS(SELECT 1
FROM FileNameStatus
WHERE FileName = :file AND Delivery = :dvry
AND SW = :sw AND FuncName = :func)
答案 2 :(得分:0)
我决定添加一个查询以检查数据是否已经存在,如下所示:
for eachRow in data:
cur.execute('''SELECT FileName, Delivery, SW, FuncName
FROM FileNameStatus
WHERE FileName = :file AND Delivery = :dvry AND SW = :sw AND FuncName = :func''',
{"file": eachRow[0], "dvry": eachRow[1], "sw": eachRow[2], "func": eachRow[3]})
row = cur.fetchone()
if row is None: # row not exist
cur.execute('''INSERT INTO FileNameStatus
(FileName, Delivery, SW, FuncName, LinkModDate, ExtSrcModDate, ExtSrcModifier,
ExtAttModDate, ExtAttModifier, Error, Warning)
VALUES (?, ?, ?, ?, ? ,? ,? ,? ,? ,? ,?)''',
eachRow)
else: # row exist, just update
cur.execute('''UPDATE FileNameStatus
SET FileName = :file, Delivery = :drvy, SW = :sw, FuncName = :func,
LinkModDate = :ld, ExtSrcModDate = :sd, ExtSrcModifier = :sm,
ExtAttModDate = :ad, ExtAttModifier = :am, Error = :err, Warning = :warn
WHERE FileName = :file AND Delivery = :drvy AND SW = :sw AND FuncName = :func;''',
{"file": eachRow[0], "drvy": eachRow[1], "sw": eachRow[2], "func": eachRow[3],
"ld": eachRow[4], "sd": eachRow[5], "sm": eachRow[6],
"ad": eachRow[7], "am": eachRow[8], "err": eachRow[9], "warn": eachRow[10]})
# apply the changes
conn.commit()