Reputation: 103
I want to make a python script that consistently checks the Mysql database and prints out new updated records every few seconds.
import time
sql_conn = connectSQLServer('ODBC Driver 13 for SQL Server', 'D\SQLEXPRESS', 'display')
mycursor = sql_conn.cursor()
a = 0
while True:
try:
time.sleep(1)
a=a+1
print(a)
sql = "SELECT id, val FROM dbo.LiveStatsFromSQLServer"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
except Exception as error:
print("Nothing in database\n")
print(error)
sql_conn.commit()
Expected output: The columns are (id, value)
1second
(1625, 3)
(1626, 0)
(1627, 10)
2second
(1625, 3)
(1626, 0)
(1627, 10)
3second
(1625, 3)
(1626, 0)
(1627, 10)
(1628,20)
Upvotes: 1
Views: 1366
Reputation: 31354
Since your records appear to start with an auto-incrementing identifier, you could do:
sql = "SELECT id, val FROM dbo.LiveStatsFromSQLServer WHERE id > %s"
mycursor.execute(sql, prev_id)
And after the print(x)
just add something like prev_id = x[0]
:
for x in myresult:
print(x)
prev_id = x[0]
Note: I don't know what the actual first column of your result is called, just replace id
with the actual column name in the script if you want to select *
instead of naming the columns (and assuming there's 2).
Upvotes: 1