我试图使用pyodbc库执行sqlselect查询,但无法从数据库中找到最后一行或最大行ID
import pyodbc
conn = pyodbc.connect(r"Driver={ODBC Driver 13 for SQL Server}; Server=XXXX; Database=sampleDb; Trusted_Connection=yes;")
cursor = conn.cursor()
cursor.execute("select Id, text from Table1 where dataexecuted IS NULL AND text is not null")
newdata = cursor.fetchall()
for l in newdata:
rowId = l.Id
rowId = max(rowId)
print(rowId)
我也尝试过用这种方法查找数据,但显示出错误
select max(Id) as lastid, Id, text from Table1 where dataexecuted IS NULL AND text is not null
可能是确切的要求还不清楚的问题。但是,如果您只是想解决错误并找到Id的最大值,那么更改
sql
查询应该会有所帮助使用哪个查询取决于您的需求
而且不需要使用
for
循环来迭代结果集,从数据库中查找max
值或任何aggregate
值,这不是一种非常有效的方法如果您只需要最大ID值,那么您可以通过一个非常简单的查询来实现这一点:
然后可以使用
cursor.fetchone()
来获取单行结果集更新:单个标量值的
fetchone()
替代方法是fetchval()
相关问题 更多 >
编程相关推荐