How to take PostgreSQL table's data constantly using Python?

Question:

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()
Asked By: Shakh

||

Answers:

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()
    
    #Closing the connection
    conn.close()
    

while True:
    fetch_data()
    print("Fetching data every one minute")
    time.sleep(1*60) # every sixty sec
    
    


Answered By: shining
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.