python 连接postgresql 数据库使用的psycopg2模块实例
1、使用pip命令安装psycopg2包
C:\Users\Douse>pip install psycopg2
Looking in indexes: https://pypi.doubanio.com/simple/Collecting psycopg2 Downloading https://pypi.doubanio.com/packages/d6/eb/ba556d3d642fedf220e2e7e4f16085d6f1f0363a1670fc4b72a26f497c5c/psycopg2-2.8.6-cp39-cp39-win_amd64.whl (1.2 MB) |████████████████████████████████| 1.2 MB 1.6 MB/sInstalling collected packages: psycopg2Successfully installed psycopg2-2.8.6
2、查看psycopg2模块的详细信息
C:\Users\Douse>pip show psycopg2
Name: psycopg2
Version: 2.8.6
Summary: psycopg2 - Python-PostgreSQL Database Adapter
Home-page: https://psycopg.org/Author: Federico Di Gregorio
Author-email: fog@initd.orgLicense: LGPL with exceptions
Location: d:\program files (x86)\python39\lib\site-packagesRequires:Required-by: 3、python 连接postgresql 实例
import psycopg2 # 导入psycopg2# 连接到一个给定的数据库conn = psycopg2.connect(database="postgres", user="postgres", password="Hjk123", host="localhost", port="5432")# 建立游标,用来执行数据库操作cursor = conn.cursor()# 执行SQL命令cursor.execute("CREATE TABLE test_conn (id int, name text)")cursor.execute("INSERT INTO test_conn values(1,'haha')")# 提交SQL命令conn.commit()# 执行SQL SELECT命令cursor.execute("select * from test_conn")# 获取SELECT返回的元组rows = cursor.fetchall()for row in rows: print('id=', row[0], 'name=', row[1], '\n')# 关闭游标cursor.close()# 关闭数据库连接conn.close()