Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    
    


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading