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

最后

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

猜你喜欢

转载自blog.csdn.net/qq_44486439/article/details/113405589