I am trying to query a Microsoft SQL database to get all records after the datetime returned in the previous loop. I use the '>' operator but the result I am seeing is for '>=' (greater than or equal).
Python (3.6.5 Win10) script:
import pyodbc # version 4.0.24
import time
import datetime
import json
con = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=mydb;UID=myuid;PWD=mypwd")
cur = con.cursor()
i = 0
lastDatetime = datetime.datetime.strptime('01Jan1970', '%d%b%Y')
while i < 60:
print("{0}: SELECT * FROM dbo.Data WHERE datetime > '{1}'".format(str(i), lastDatetime))
cur.execute("SELECT * FROM dbo.Data WHERE datetime > ?", lastDatetime)
rows = cur.fetchall()
for k, v in enumerate(rows):
jsonMsg = json.dumps({
"transaction_id": v[1],
"plu": v[2].strip(),
"qty": int(v[3]),
"dateTime": str(v[4])
}, separators=(',', ':'))
print(str(jsonMsg))
lastDatetime = v[6]
print("lastDatetime set to: {0}".format(lastDatetime))
i = i + 1
time.sleep(5)
Produces:
0: SELECT * FROM dbo.Data WHERE datetime > '1970-01-01 00:00:00'
{"transaction_id":3201,"plu":"3","qty":1,"dateTime":"2018-08-01 10:45:40.560000"}
lastDatetime set to: 2018-08-01 10:45:40.560000
{"transaction_id":3202,"plu":"5","qty":1,"dateTime":"2018-08-01 10:45:51.563000"}
lastDatetime set to: 2018-08-01 10:48:47.653000
{"transaction_id":3230,"plu":"8","qty":2,"dateTime":"2018-08-01 10:48:47.653000"}
lastDatetime set to: 2018-08-01 10:48:47.653000
1: SELECT * FROM dbo.Data WHERE datetime > '2018-08-01 10:48:47.653000'
{"transaction_id":3230,"plu":"8","qty":2,"dateTime":"2018-08-01 10:48:47.653000"}
lastDatetime set to: 2018-08-01 10:48:47.653000
2: SELECT * FROM dbo.Data WHERE datetime > '2018-08-01 10:48:47.653000'
{"transaction_id":3230,"plu":"8","qty":2,"dateTime":"2018-08-01 10:48:47.653000"}
lastDatetime set to: 2018-08-01 10:48:47.653000
I run the query in SQL Server Management Studio and I get the expected result:
SELECT * FROM dbo.Data WHERE datetime > '2018-08-01 10:48:47.653'
returns no records.
What am I missing or what should I change in the python script to get the expected result?
Thanks.
EDITS: Add the '' to the print of the sql string around the datatime. Didn't make a difference to the result.