Posted on Leave a comment

Python Script to Query POSTGRESQL Database

Here is a basic Python script to query a PostgreSQL database using the “psycopg2” library. Very useful for data mining.

import psycopg2

conn = psycopg2.connect(
    host="hostname",
    database="database_name",
    user="username",
    password="password"
)

cursor = conn.cursor()

query = "SELECT * FROM table_name"
cursor.execute(query)

result = cursor.fetchall()

for row in result:
    print(row)

conn.close()

Replace the placeholders with the appropriate values for your database:

  • “hostname” is the address of the database server
  • “database_name” is the name of the database you want to connect to
  • “username” and “password” are the credentials used to access the database
  • “table_name” is the name of the table you want to query.

You can modify the SELECT statement to retrieve specific columns or filter the data as desired.

Leave a Reply

Your email address will not be published. Required fields are marked *