使用python脚本(数据库URI)连接到postgresql,但检测到';康涅狄格州';作为字符串
我正在使用一个简单的python脚本连接postgresql,future将使用该脚本将表创建到postgresql中 我的代码是:使用python脚本(数据库URI)连接到postgresql,但检测到';康涅狄格州';作为字符串,python,postgresql,connection,database-connection,Python,Postgresql,Connection,Database Connection,我正在使用一个简单的python脚本连接postgresql,future将使用该脚本将表创建到postgresql中 我的代码是: try: conn = "postgresql://postgres:<password>@localhost:5432/<database_name>" print('connected') except: print('not connected') conn.close() 非常确
try:
conn = "postgresql://postgres:<password>@localhost:5432/<database_name>"
print('connected')
except:
print('not connected')
conn.close()
非常确定的是,它将“conn”检测为字符串,而不是数据库连接。我遵循了这一点(33.1.1.2),但现在确定我是否做对了。如何更正此代码,使其将脚本连接到我的postgresql server,而不只是将其检测为字符串
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()
您可以按此操作…是的
conn
肯定是一个字符串,因此没有commit()
或close()
方法。其值为“postgresql://postgres:@localhost:5432/“
。你的意思是像conn=psycopg2.connect(“postgresql://postgres:@localhost:5432/”
?请注意,您链接到其文档的libpq
,是一个C库,而不是Python库。您向我们展示的代码没有生成该错误消息。其中没有commit()
。在这里提问时,请务必提供答案。
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()