0

I have the following code in 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 is unique in MSSQL DB. Could I use something like insert or replace in SQLite? which does not work in MSSQL.

1

1 Answer 1

1

You can use Merge in MSSQL

So replace your

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

As follows;

MERGE INTO dbo.printedPaths WITH (HOLDLOCK) AS target USING (SELECT pth 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);

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()
Sign up to request clarification or add additional context in comments.

10 Comments

Thank you, I will try it on monday, because I'm on Linux now.
Could you please show the whole cur.execute() statement, I'm not quite clear about it.
@xralf, you better try it :) - Read the answer again and give it a shot.
It ends with error: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '@P1'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")
@xralf, In your question there is no '@P1', so the problem should be elsewhere.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.