python 之 连接postgresql 数据库简单实例

python 连接 postgresql 数据库简单案例
首先创建一个测试文件 test.py,然后把一下代码拷贝到文件中
这里注意的是 需要引 psycopg2 这个包

import psycopg2

# 创建连接
conn = psycopg2.connect(database='db',user='root',password='root',host='120.0.0.1',port='5432')
# 创建指针对象
cur = conn.cursor()
# 执行sql
res = cur.execute('select * from di_connect_config order by id');
# 获取查询到的所有数据
data = cur.fetchall()
# 打印查询到的内容
print(data)
print('共发现了',len(data),'条数据')
# for i in data:
#     print(i[2])
# 关闭数据库连接
conn.close()

执行test.py文件, 命令:python test.py
以上即为连接postgresql 简单案例;

你可能感兴趣的:(python,postgresql,python)