DEV Community

Cover image for Connect to a PostgreSQL database(python).
AYON KARMAKAR
AYON KARMAKAR

Posted on • Edited on

13 4 4 4 4

Connect to a PostgreSQL database(python).

connecting to a PostgreSQL database from Python.

Installation:

  • Install PostgreSQL, If you haven’t installed it.
  • We need to install the psycopg2 library to connect to a PostgreSQL database. Open the command prompt and run the below command to install psycopg2 ```bash

pip3 install psycopg2

# Creating a Database
You can create a Database in 2 Ways:
1. Using pgAdmin 4 UI
2. Using command

**1. Using pgAdmin 4 UI**
Go to pgAdmin and Follow these Steps.
- Local_server[Right Click] -> Create -> Database 
![Img](https://media.geeksforgeeks.org/wp-content/uploads/20220822143634/pgadmin4CreatingaDatabase.png)
- Next, Fill out the form Database:  WorkSpace and Save.

**2. Create Database Using SQL query**
Go to pgAdmin and follow these Steps:
- Run the below Command in the Query tab
Enter fullscreen mode Exit fullscreen mode

CREATE DATABASE WorkSpace;

![img](https://media.geeksforgeeks.org/wp-content/uploads/20220822174010/Createdatabaseusingcomand.jpg)
## Connecting to the database
We need to connect to a PostgreSQL database using psycopg2.connect() function.
**Where the attributes of connect() function are:**
```python


host = hostname,
dbname = databaseName,
user = username,
password = [Your Password],
port = [port_id]


Enter fullscreen mode Exit fullscreen mode

In case you don’t know any of these connect() function attributes, you can follow the below steps:
umg

Now You Know All the properties of this Database. Let’s continue.

Now, to connect to the database, we need to pass the attributes as arguments to the connect() function.

Syntax:



conn = psycopg2.connect(
    host = 'localhost',
    dbname = 'For_Practice',
    user = 'postgres',
    password = '[Password]',
    port = 5432
)


Enter fullscreen mode Exit fullscreen mode

Create a cursor:

  • Create a cursor(i.e., curr) object and call its execute() method to execute queries.
  • Where execute() method is used to run a query that is passed as a string. Syntax: ```python

cur = conn.cursor()
cur.execute('[SQL queries]')

In the end, We need to save the changes using commit() method and finally close the opened connection using `close()` method.
```python


conn.commit()
cur.close()


Enter fullscreen mode Exit fullscreen mode


import psycopg2

conn = None
try:
    # connect to the PostgreSQL server
    print('Connecting to the PostgreSQL database...')
    conn = psycopg2.connect(
        host = 'localhost',
        dbname = 'For_Practice',
        user = 'postgres',
        password = '321654',
        port = 5432
    )

    # Creating a cursor with name cur.
    cur = conn.cursor()
    print('Connected to the PostgreSQL database')

    # Execute a query:
    # To display the PostgreSQL
    # database server version
    cur.execute('SELECT version()')
    print(cur.fetchone())

    # Close the connection
    cur.close()

except(Exception, psycopg2.DatabaseError) as error:
    print(error)
finally:
    if conn is not None:
        conn.close()
        print('Database connection closed.')



Enter fullscreen mode Exit fullscreen mode

ACI image

ACI.dev: Best Open-Source Composio Alternative (AI Agent Tooling)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Star our GitHub!

Top comments (1)

Collapse
 
kasir-barati profile image
Mohammad Jawad (Kasir) Barati

Just one comment, please encourage people to use venv or comparable approaches

Postmark Image

"Please fix this..."

Focus on creating stellar experiences without email headaches. Postmark's reliable API and detailed analytics make your transactional emails as polished as your product.

Start free

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️