Explore the powerful psycopg2 library, the go-to Postgres driver for Python. Learn how to seamlessly integrate PostgreSQL with Python using this robust database adapter.
pip install psycopg2What is psycopg2 and why use it?
Key features and capabilities
Installation instructions
Basic usage examples
Common use cases
Best practices and tips
import psycopg2\n\n# Establish a connection to the PostgreSQL database\nconn = psycopg2.connect(\n dbname='your_dbname', \n user='your_user', \n password='your_password', \n host='localhost'\n)\n\n# Create a cursor object\ncur = conn.cursor()\n\n# Execute a query\ncur.execute('SELECT version()')\n\n# Fetch and display the result\nrecord = cur.fetchone()\nprint('You are connected to - ', record, '\
')\n\n# Close the cursor and connection\ncur.close()\nconn.close()import psycopg2\n\n# Advanced example with error handling\ntry:\n # Connect to your postgres DB\n conn = psycopg2.connect('dbname=test user=postgres password=secret')\n\n # Open a cursor to perform database operations\n with conn.cursor() as cur:\n # Execute a command: this creates a new table\n cur.execute('CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);')\n\n # Pass data to fill a query placeholders and let Psycopg perform\n cur.execute('INSERT INTO test (num, data) VALUES (%s, %s)', (100, "abc'def"))\n\n # Query the database and obtain data as Python objects\n cur.execute('SELECT * FROM test;')\n cur.fetchall()\n\n # Close communication with the database\n conn.commit()\nexcept Exception as e:\n print(f'An error occurred: {e}')\nfinally:\n conn.close()connectEstablishes a connection to a PostgreSQL database.
cursorCreates a new cursor object for database operations.
executeExecutes a database operation (query or command).