我目前正在使用 AWS Lambda 实现一个 API,将数据插入 SQL Server 数据库。 我正在使用Python 3.11。 代码执行成功并返回200状态码, 但是当我在 SSMS 中运行 SELECT 查询时, 它会导致无限执行。 我需要帮助来解决这个问题。
这是我的代码:
conn_str = (
f'Driver={{ODBC Driver 17 for SQL Server}};'
f'Database=TMP;'
f'Encrypt=no;'
)
data = [{
"sfid" : "aws1123124",
"lastmodifieddate" : "a551231",
"comments" : "a11231",
"keyword" : "a41231231",
"productcode" : "s55234234",
"serialNumber" : "d1123123"
}]
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
cursor.execute("BEGIN TRANSACTION")
try :
for record in data:
print("in record")
print(record['sfid'])
merge_sql = """
MERGE INTO [dbo].[LocalDB] AS Target
USING (SELECT ? AS sfid, ? AS lastmodifieddate, ? AS comments, ? AS keyword, ? AS productcode, ? AS serialNumber) AS Source
ON Target.sfid = Source.sfid
WHEN MATCHED THEN
UPDATE SET
lastmodifieddate = Source.lastmodifieddate,
comments = Source.comments,
keyword = Source.keyword,
productcode = Source.productcode,
serialNumber = Source.serialNumber
WHEN NOT MATCHED THEN
INSERT (sfid, lastmodifieddate, comments, keyword, productcode, serialNumber)
VALUES (Source.sfid, Source.lastmodifieddate, Source.comments, Source.keyword, Source.productcode, Source.serialNumber);
"""
cursor.execute(merge_sql,
record['sfid'],
record['lastmodifieddate'],
record['comments'],
record['keyword'],
record['productcode'],
record['serialNumber'])
conn.commit()
except Exception as e:
cursor.execute("ROLLBACK")
print(f"An error occurred: {e}")
raise e
finally:
if cursor is not None:
try:
cursor.close()
except Exception as ex:
print(f"Error closing cursor: {ex}")
if conn is not None:
try:
conn.close()
except Exception as ex:
print(f"Error closing connection: {ex}")
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
我只是更改了您的代码以删除
cursor.execute("BEGIN TRANSACTION")
和 cursor.execute("ROLLBACK")
,然后在 cursor.commit()
中添加 try
,没有任何问题。我还按照链接的 文章列表 中的建议,向 HOLDLOCK
添加了 MERGE
提示(不过,最好还是使用 upsert)。这是有意压缩的,但这实际上变成了:
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
try :
for record in data:
print("in record")
print(record['sfid'])
merge_sql = """
MERGE INTO [dbo].[LocalDB] WITH (HOLDLOCK) AS Target
...
"""
cursor.execute(merge_sql,
record['sfid'],
record['lastmodifieddate'],
record['comments'],
record['keyword'],
record['productcode'],
record['serialNumber'])
cursor.commit()
except Exception as e:
print(f"An error occurred: {e}")
raise e
finally:
...