Edits history of script submission #1043 for ' python- connect to a database and query for data (postgresql)'

  • python3
    import psycopg2
    
    def main():
    
        db_params = {
            'dbname': 'areallycooldatabase',
            'user': 'anevenbetterusername',
            'password': 'cleartextpassword?whynot!',
            'host': 'ip address or hostname',
            'port': '5432' # 5432 is PostgreSQL default port
        }
    
        table = 'table' # example table value
        sql = f"SELECT * FROM {table} limit 10;" # draft your SQL command here. Use triple """ if you need extra formatting space.
    
        # Establish a connection to the PostgreSQL database
        conn = psycopg2.connect(**db_params)
        cursor = conn.cursor()
    
        cursor.execute(sql)
    
        results = cursor.fetchall()
    
        print(results)
    

    Submitted by matt latham979 1003 days ago