简体   繁体   English

每隔几秒从python中的SQL中获取新数据

[英]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.我想制作一个 python 脚本,它可以一致地检查 Mysql 数据库并每隔几秒钟打印出新的更新记录。

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)预期输出:列是 (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] :print(x)之后,只需添加类似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).注意:我不知道结果的实际第一列是什么,如果您想select *而不是命名列(并假设有 2 个),只需将id替换为脚本中的实际列名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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