如何使用 Python 不斷地獲取 PostgreSQL 表的資料?(例如,每 1 分鐘,它需要獲取下一行的資料)你能幫我嗎?
import psycopg2
#establishing the connection
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Setting auto commit false
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving data
cursor.execute('''SELECT * from EMPLOYEE''')
#Fetching 1st row from the table
result = cursor.fetchone();
print(result)
#Fetching 1st row from the table
result = cursor.fetchall();
print(result)
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
uj5u.com熱心網友回復:
您可以使用while回圈并timer執行代碼,如下所示。
import psycopg2
import time
#establishing the connection
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Setting auto commit false
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
def fetch_data():
#Retrieving data
cursor.execute('''SELECT * from EMPLOYEE''')
#Fetching 1st row from the table
result = cursor.fetchone();
print(result)
#Fetching 1st row from the table
result = cursor.fetchall();
print(result)
#Commit your changes in the database
conn.commit()
while True:
fetch_data()
print("Fetching data every one minute")
time.sleep(1*60) # every sixty sec
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/527313.html
下一篇:postgres更改表列被跳過
