admin 发表于 2020-5-31 07:52:36

python连接postgresql

1.客户端安装psycopg2
C:\Users\zhyu>pip install psycopg2
Collecting psycopg2
Using cached psycopg2-2.8.5-cp38-cp38-win_amd64.whl (1.1 MB)
Installing collected packages: psycopg2
Successfully installed psycopg2-2.8.52.服务端启动postgresql
$ pg_ctl start
waiting for server to start....2020-05-31 07:40:41.254 CST LOG:starting PostgreSQL 12.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit
2020-05-31 07:40:41.254 CST LOG:listening on IPv4 address "0.0.0.0", port 5432
2020-05-31 07:40:41.254 CST LOG:listening on IPv6 address "::", port 5432
2020-05-31 07:40:41.332 CST LOG:listening on Unix socket "/tmp/.s.PGSQL.5432"
2020-05-31 07:40:41.517 CST LOG:redirecting log output to logging collector process
2020-05-31 07:40:41.517 CST HINT:Future log output will appear in directory "/app/postgres/12/data".
done
server started3.进入python环境
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
4.加载psycopg2
import psycopg2
5.建立连接符
conn=psycopg2.connect(database="postgres",user="postgres",password="postgres",host="192.168.56.101",port="5432")
6.建立游标
cursor=conn.cursor()
7.执行sql
cursor.execute("select version()")
8.获取结果
>>> results=cursor.fetchall()
>>> print(results)
[('PostgreSQL 12.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit',)]9.关闭游标
cursor.close()10.关闭连接
conn.close()
整体流程步骤:
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
>>> conn=psycopg2.connect(database="postgres",user="postgres",password="postgres",host="192.168.56.101",port="5432")
>>> cursor=conn.cursor()
>>> cursor.execute("select version()")
>>> results=cursor.fetchall()
>>> print(results)
[('PostgreSQL 12.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit',)]
>>> cursor.close()
>>> conn.close()
>>>



页: [1]
查看完整版本: python连接postgresql