0

python- connect to a database and query for data

by
Published Sep 30, 2023

Connect to a postgresql database using parameters you specify within the script. Print the results of the query to the console.

Script postgresql
  • Submitted by matt latham979 Python3
    Created 1003 days ago
    1
    import psycopg2
    2
    
    
    3
    def main():
    4
    
    
    5
        db_params = {
    6
            'dbname': 'areallycooldatabase',
    7
            'user': 'anevenbetterusername',
    8
            'password': 'cleartextpassword?whynot!',
    9
            'host': 'ip address or hostname',
    10
            'port': '5432' # 5432 is PostgreSQL default port
    11
        }
    12
    
    
    13
        table = 'table' # example table value
    14
        sql = f"SELECT * FROM {table} limit 10;" # draft your SQL command here. Use triple """ if you need extra formatting space.
    15
    
    
    16
        # Establish a connection to the PostgreSQL database
    17
        conn = psycopg2.connect(**db_params)
    18
        cursor = conn.cursor()
    19
    
    
    20
        cursor.execute(sql)
    21
    
    
    22
        results = cursor.fetchall()
    23
    
    
    24
        print(results)
    25