Home > Back-end >  How to take PostgreSQL table's data constantly using Python?
How to take PostgreSQL table's data constantly using Python?

Time:11-04

How to take PostgreSQL table's data constantly using Python? (For example, every 1 minute, it needs to take the next row's data) Could you please help me with that?

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

CodePudding user response:

You can use while loop and timer to execute your code as shown below.

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
    
    


  • Related