我运行 python 容器,我想连接 localhost postegresql。我尝试一些方法。但不工作。请跟我谈谈。我能怎么做 ?谢谢。
我已经在端口 5432 上运行 postegresql,创建数据库并授予用户。
运行 docker 命令
docker run --name=python3 -v ${pwd}:/code -w /code python
Run Code Online (Sandbox Code Playgroud)
蟒蛇代码
import psycopg2
def main():
#Define our connection string
conn_string = "host='localhost' dbname='testDB' user='test' password='test'"
# print the connection string we will use to connect
print ("Connecting to database\n ->{}".format(conn_string))
# get a connection, if a connect cannot be made an exception will be raised here
conn = psycopg2.connect(conn_string)
# conn.cursor will return a cursor object, you can use …Run Code Online (Sandbox Code Playgroud)