我有一个连接到sql server实例的python脚本。我运行cte查询以删除重复项。查询成功运行,但是当我使用fetchall()函数时,会导致错误:上一个查询不是sql查询,并且在db表中检查了重复项后,它显示重复项仍然存在。 pyodbc和sqlalchemy都是这种情况。
代码pyodbc:
import pyodbc
conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
query = ''';with cte as
(
SELECT [ID], [TIME], ROW_NUMBER() OVER
(PARTITION BY [ID] order by [TIME] desc) as rn
from table
)delete from cte WHERE rn > 1'''
cursor.execute(query)
cursor.close()
conn.close()
Code for sqlalchemy:
from sqlalchemy import create_engine
from sqlalchemy.sql import text
import urllib
conn = urllib.parse.quote_plus(connection_string)
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(conn))
query = '''with cte as
(
SELECT [ID], [TIME], ROW_NUMBER() OVER (PARTITION BY [ID] order by [TIME] desc) as rn
from table
)
delete from cte WHERE rn > 1'''
connect = engine.connect()
result = connect.execute(query)
if result.returns_rows:
print("Duplicates removed")
else:
print("No row is returned")
答案 0 :(得分:2)
当我使用fetchall()函数时,会导致错误:上一个查询不是sql查询
这是预期的行为。尽管您的查询包括SELECT作为CTE的一部分,但查询本身最终是一个DELETE查询,它不返回行。它将返回可以用Cursor#rowcount检索的行计数,但是Cursor#fetchall()将抛出错误,因为没有要检索的行。