简体   繁体   English

如何在程序运行时使用python从数据库中获取新数据而不刷新我的程序

[英]How I fetch new data from database while the program is running using python without refresh my program

I want to fetch newly added data from my database while the program is running without refreshing the program using python...How can I do that ?? 我想在程序运行时从我的数据库中获取新添加的数据而不使用python刷新程序...我该怎么做?

import mysql.connector

mydb = mysql.connector.connect(
    host ="localhost",
    user = "root",
    password = "",
    database = "databasename"
)

mycursor = mydb.cursor()

def fetchdata():
        mycursor.execute("SELECT * FROM tablename")
        myresult = mycursor.fetchall()
        for data in myresult:
            u_id = data[0]
            username = data[1]
            email = data[2]
            password = data[3]
            print(f"{u_id},{username},{email},{password}")

if __name__ == '__main__':
    while True: # for fetching data again again and again
        fetchdata()

If you have a timestamp column in your table (if not you should add one) you can save that to a variable and fetch data added after that point in time. 如果表中有时间戳列(如果不是,则应添加一个),可以将其保存到变量并获取在该时间点之后添加的数据。

Lets say before your first fetch you have the following in your table 让我们说,在您第一次获取之前,您在表中有以下内容

id, username, email, password, loaded_at
1, user1, 123@mail.com, ***, 2019-05-03 11:12:12
2, user2, 456@mail.com, ***, 2019-05-03 11:14:34
3, user3, 789@mail.com, ***, 2019-05-03 11:16:56

After your first query keep max(loaded_at) in a variable let's call it max_loaded_at 在第一次查询后,将max(loaded_at)保留在变量中,让我们称之为max_loaded_at

Assume two new rows added to data 假设向数据添加了两个新行

id, username, email, password, loaded_at
4, user4, 124@mail.com, ***, 2019-05-03 11:17:55
5, user5, 457@mail.com, ***, 2019-05-03 11:21:47

in your code change your query to 在您的代码中将您的查询更改为

mycursor.execute(f"SELECT * FROM tablename WHERE loaded_at > '{max_loaded_at}'")

This will give you new rows for id 4 and 5 这将为id 4和5提供新行

Do not forget to initialize your variable to a time earlier than your min date, something like 不要忘记将变量初始化为早于最小日期的时间,例如

max_loaded_at = '2001-01-01'

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

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