Python连接PostgreSQL数据库
Python连接PostgreSQL数据库环境Python 3.7.4psycopg2==2.8.5PostgreSQL 12.4pip安装pip install psycopg2实现代码其中<hostname>为PostgreSQL数据库的IP地址,本地为localhost;<port>为端口号,PostgreSQL默认端口号为5432;<user name>
·
Python连接PostgreSQL数据库
环境
Python 3.7.4
psycopg2==2.8.5
PostgreSQL 12.4
pip安装
pip install psycopg2
实现代码
其中<hostname>
为PostgreSQL
数据库的IP地址,本地为localhost
;<port>
为端口号,PostgreSQL
默认端口号为5432
;<user name>
和<password>
分别为用户名和密码;<database name>
为数据库名
import psycopg2
if __name__ == "__main__":
connection = psycopg2.connect(host="<hostname>", port="<port>", user="<user name>", password="<password>", database="<database name>")
cursor = connection.cursor()
# 查询PostgreSQL数据库中的所有数据库
cursor.execute("select datname from pg_database")
result = cursor.fetchall()
cursor.close()
connection.close()
print(result)
测试结果
[('postgres',), ('template1',), ('template0',)]
最后
- 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)