使用 python 脚本(数据库 URI)连接到 postgresql 但检测到 'conn' 作为字符串

Connect to postgresql using python script (database URI) but detects 'conn' as string

我正在使用一个简单的 python 脚本来连接 postgresql,将来只需使用该脚本即可将 table 创建到 postgresql 中。

我的代码是:

try:
    conn =  "postgresql://postgres:<password>@localhost:5432/<database_name>"
    print('connected')

except:
    print('not connected')

conn.close() 

当我 运行 python connect.py (我的文件名)时,它抛出这个错误:

Instance of 'str' has no 'commit' member

很确定是因为它将 'conn' 检测为字符串而不是数据库连接。我已经遵循了这个 documentation (33.1.1.2) 但现在确定我是否做对了。如何更正此代码以便它将脚本连接到我的 postgresql 服务器而不是仅仅将其检测为字符串?

p/s:我对此很陌生。

您正在尝试调用字符串对象的方法。 相反,您应该首先建立与数据库的连接。

我不知道允许使用完整连接字符串的驱动程序,但您可以使用 psycopg2,它是 PostgreSQL 的常见 python 驱动程序。

安装 psycopg2 之后,您可以执行以下操作来建立连接并请求您的数据库

import psycopg2
try:
    connection = psycopg2.connect(user = "yourUser",
                                  password = "yourPassword",
                                  host = "serverHost",
                                  port = "serverPort",
                                  database = "databaseName")

    cursor = connection.cursor()
except (Exception, psycopg2.Error) as error :
    print ("Error while connecting", error)
finally:
        if(connection):
            cursor.close()
            connection.close()

你可以关注这个tutorial