简体   繁体   中英

Fetch new data from SQL in python every few seconds

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)

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM