简体   繁体   中英

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 ??

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

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

Do not forget to initialize your variable to a time earlier than your min date, something like

max_loaded_at = '2001-01-01'

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