在python的mssql中插入或替换

ma8fv8wu  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(330)

我用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` 是 `unique` 在mssql数据库中。我能用一下吗 `insert or replace` 在sqlite中?在mssql中不起作用。
s4n0splo

s4n0splo1#

你可以用 MergeMSSQL 所以把你的

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

具体如下:;
合并到dbo.printedpaths,以(holdlock)为目标,在(target.pth=source.pth)上使用(select pth pth,tm)作为源(pth,tm),匹配时更新set 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()

相关问题