我试图在一个固定的时间间隔后从随记录增长的数据库表中获取记录。我正在使用 Python 及其 pyodbc 包来执行记录的获取。在获取时,如何将光标指向最后读取/获取的行的下一行,以便每次获取时我只能插入新的记录集。
为了解释更多, 我的表有 100 条记录,它们已被提取。 一段时间后,该表有 200 条记录,我想获取从 101 到 200 的行。依此类推。
pyodbc 游标有办法吗? 或者任何其他建议都会非常有帮助。
下面是我正在尝试的代码:
#!/usr/bin/python
import pyodbc
import csv
import time
conn_str = (
"DRIVER={PostgreSQL Unicode};"
"DATABASE=postgres;"
"UID=userid;"
"PWD=database;"
"SERVER=localhost;"
"PORT=5432;"
)
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
def fetch_table(**kwargs):
qry = kwargs['qrystr']
try:
#cursor = conn.cursor()
cursor.execute(qry)
all_rows = cursor.fetchall()
rowcnt = cursor.rowcount
rownum = cursor.description
#return (rowcnt, rownum)
return all_rows
except pyodbc.ProgrammingError as e:
print ("Exception occured as :", type(e) , e)
def poll_db():
for i in [1, 2]:
stmt = "select * from my_database_table"
rows = fetch_table(qrystr = stmt)
print("***** For i = " , i , "******")
for r in rows:
print("ROW-> ", r)
time.sleep(10)
poll_db()
conn.close()
最佳答案
我认为您不能使用 pyodbc 或任何其他 odbc 包来查找"new"行。但是如果你的数据库中有一个“时间戳”列,或者如果你可以添加这样一个列(一些数据库允许它自动填充为插入时间所以你不必更改插入查询)那么你可以更改您的查询以仅选择时间戳大于前一个时间戳的行。您可以在每次迭代中不断更改 prev_timestamp 变量。
def poll_db():
prev_timestamp = ""
for i in [1, 2]:
if prev_timestamp == "":
stmt = "select * from my_database_table"
else:
# convert your timestamp str to match the database's format
stmt = "select * from my_database_table where timestamp > " + str(prev_timestamp)
rows = fetch_table(qrystr = stmt)
prev_timestamp = datetime.datetime.now()
print("***** For i = " , i , "******")
for r in rows:
print("ROW-> ", r)
time.sleep(10)
关于python - 如何在 Python 中使用 pyodbc 将光标更改到下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37478497/