如何将Python连接到PostgreSQL

时间:2014-10-21 21:10:25

标签: python postgresql

在Google上,我找到了有关PyGreSQL库的文档,可以帮助我将Python连接到Postgres。

但是,我无法在任何地方找到下载软件包的链接。甚至这个文件: http://www.pygresql.org/install.html

谈论下载Windows Installer等,但不知道从哪里开始。

我希望连接适用于Python 2.7

4 个答案:

答案 0 :(得分:2)

从python进入PostgreSQL的最经典且文档最好的库可能是psycopg2,可以为windows here下载。 如果您特别想要PyGreSQL,则下载页面为here

答案 1 :(得分:2)

pypi https://pypi.python.org上列出了不属于标准库的Python模块。 例如,pygresql模块列在以下页面中: https://pypi.python.org/pypi/PyGreSQL/

您还可以在页面上看到上次更新软件包(在本例中为2013),因此您可以使用psycopg2等替换方法,使用python连接到postgresql https://pypi.python.org/pypi/psycopg2

答案 2 :(得分:2)

例如,如果您在docker中使用了PostreSQL

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

您没有安装psycopg2,对于此变体,您可以安装psycopg2-binary

pip install psycopg2-binary

之后可以使用

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)

答案 3 :(得分:0)

第1步:pip安装psycopg2

第2步:用户输入以下代码:-

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)