Goal:
I am aiming to compare the last result to new result, every time the function runs.
Code:
starttime = time.time()
def countRows():
while True:
#Get number of rows from SQL table
sqlCursor = sqlConnection.cursor()
sqlCursor.execute("Select count(*) from SalesOrder")
rowcount = sqlCursor.fetchone()[0]
print(rowcount)
if rowcount != rowcount:
print("changed")
time.sleep(10.0 - ((time.time() - starttime) % 10.0))
countRows()
Details:
Here I am getting count from SQL table.
This is the output every 10 seconds:
1000
1000
1000
1000
If a record is added to sql table, the count obviously changes to 1001.
Problem with current code:
The if statement does not work - when the number changes. It just prints the number.
Question:
Whilst the function is running every 10 seconds. How can I
trigger print("changed") if the value is not same as previous value?
you are comparing the same variable with itself:
if rowcount != rowcount:
you should use an intermediate variable to store the previous count: something like:
prev_rowcount = None
...
if prev_rowcount != None and prev_rowcount != rowcount:
print("changed")
prev_rowcount = rowcount
Think this will work:
starttime = time.time()
def countRows():
prev_rowcount = None
while True:
#Get number of rows from SQL table
sqlCursor = sqlConnection.cursor()
sqlCursor.execute("Select count(*) from SalesOrder")
rowcount = sqlCursor.fetchone()[0]
print(rowcount)
if rowcount != prev_rowcount and prev_rowcount != None:
print("changed")
prev_rowcount = rowcount
time.sleep(10.0 - ((time.time() - starttime) % 10.0))
countRows()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With