在 Python 中的 SQL 中插入或替换

Insert or replace in MSSQL in Python

我在python中有以下代码:

import pyodbc

def insertPrintedPath(self, pth):

        con = pyodbc.connect('blabla')
        cur = con.cursor()
        tm = str(datetime.datetime.now())

        cur.execute("insert into dbo.printedPaths \
                    (pth, tm) values \
                    (?, ?)", pth, tm)
        cur.close()
        con.commit()
        con.close()

pth 在 MSSQL 数据库中是 unique。我可以在 SQLite 中使用类似 insert or replace 的东西吗? 这在 MSSQL 中不起作用。

您可以在 MSSQL

中使用 Merge

所以更换你的

insert into dbo.printedPaths \
                    (pth, tm) values \

如下;

合并 INTO dbo.printedPaths WITH (HOLDLOCK) 作为目标 USING (SELECT pth pth, tm) 作为源 (pth, tm) 打开(target.pth = source.pth) 匹配后更新 设置 tm = tm 不匹配时 然后插入 (pth, tm) 值 (pth, tm);

def insertPrintedPath(self, pth):

        con = pyodbc.connect('blabla')
        cur = con.cursor()
        tm = str(datetime.datetime.now())

        cur.execute("    MERGE \
    INTO dbo.printedPaths WITH (HOLDLOCK) AS target \
    USING (SELECT pth, tm) AS source (pth, tm) \
    ON (target.pth = source.pth) \
    WHEN MATCHED  THEN UPDATE \
        SET tm = tm \
    WHEN NOT MATCHED \
        THEN INSERT (pth, tm) VALUES  \
                    (?, ?)", pth, tm)
        cur.close()
        con.commit()
        con.close()