user3422637
user3422637

Reputation: 4239

How to connect Python to PostgreSQL

On googling, I found documents about PyGreSQL library that would help me connect Python to Postgres.

However, I cannot find the link to download the package anywhere. Even this document: http://www.pygresql.org/install.html

talks about downloading the Windows Installer etc, but doesn't tell from where.

I want the connection to work for Python 2.7

Upvotes: 13

Views: 60470

Answers (4)

Nikolay Baranenko
Nikolay Baranenko

Reputation: 1675

if you used PostreSQL in docker, for example

docker pull postgres

mkdir -p $HOME/docker/volumes/postgres

docker run --rm --name pg-docker -e POSTGRES_PASSWORD=docker -d -p 5432:5432 -v $HOME/docker/volumes/postgres:/var/lib/postgresql/data postgres

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
850f9ee04731        postgres            "docker-entrypoint.s…"   44 hours ago        Up 44 hours         0.0.0.0:5432->5432/tcp   pg-docker

you don't install psycopg2, for this variant you can install psycopg2-binary

pip install psycopg2-binary

after can use for example

import psycopg2

connection = psycopg2.connect(database="postgres", user='postgres', password='docker', host="localhost", port=5432)

cursor = connection.cursor()

sql_context ="""
select 
    *
from 
    public.metrics sm
where 
    sm.metric_name not like '%test%'
group by 
    sm.metric_name
"""


cursor.execute(sql_context)

# Fetch all rows from database
record = cursor.fetchall()

print("Data from Database:- ", record)

Upvotes: 6

sandeep shewale
sandeep shewale

Reputation: 223

Step 1: pip install psycopg2

Step 2: User below code:-

import psycopg2

connection = psycopg2.connect(database="dbname", user="username", password="pass", host="hostname", port=5432)

cursor = connection.cursor()

cursor.execute("SELECT * from portal.portal_users;")

# Fetch all rows from database
record = cursor.fetchall()

print("Data from Database:- ", record)

Upvotes: 15

Ara
Ara

Reputation: 325

The most classical and well documented library to tap into PostgreSQL from python is probably psycopg2 which can be download for windows here. If you specifically want PyGreSQL the download page is here.

Upvotes: 2

user1658078
user1658078

Reputation: 132

Python modules that are not part of the standard library are listed on pypi https://pypi.python.org. So for example the pygresql module is listed in the following page: https://pypi.python.org/pypi/PyGreSQL/

You can also see in the page the last time the package was updated (in this case 2013), so you have alternatives like psycopg2, to connect to postgresql using python https://pypi.python.org/pypi/psycopg2

Upvotes: 2

Related Questions