简体   繁体   中英

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

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)

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)

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM