Python连接PostgreSQL数据库

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',)]

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...