【问题标题】:How can I connect Postgres database from Google Colab?如何从 Google Colab 连接 Postgres 数据库?
【发布时间】:2019-05-04 10:00:43
【问题描述】:

我可以通过上传数据库文件并执行以下命令从 Google Colab 连接 sqlite:

import sqlite3
con = sqlite3.connect('new.db')
cur = con.cursor()
cur.execute("SELECT * FROM page_log") # page_log is a table name in the new.db.
cur.fetchone()

这很好用,因为我们可以在 sqlite 中上传数据库文件,因为它的性质。对于postgres,情况不是那么清楚,至少我不知道该怎么做。我检查了this 并实现为:

%sql postgres://postgres:1234@postgres/postgres

但它不起作用。错误信息:

Connection info needed in SQLAlchemy format, example:
           postgresql://username:password@hostname/dbname
           or an existing connection: dict_keys([])

我也试过了:

from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine("postgres://postgres:1234@localhost:5432")
db = scoped_session(sessionmaker(bind=engine))
db.execute("SELECT * FROM page_log").fetchall()

错误:

OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?

最后,这也没有用。

db = psycopg2.connect(host='localhost', port=5432, user='postgres',
                          password='1234', dbname='postgres')

错误信息:

OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?

我找不到解决方案。非常感谢您的帮助!

【问题讨论】:

  • SQLite3 只是在您想要的任何地方运行在内存中的库。这就是它的美妙之处。但是 PostgreSQL 必须安装在某个地方,并且您将使用正确的 IP 连接到它。也看看这个stackoverflow.com/questions/47216559/…

标签: postgresql google-colaboratory


【解决方案1】:

就像 JosMac 建议的那样,PostgreSQL 必须安装在某个地方。

以下是一种解决方法(假设您使用的是 Mac):

  • 在本地安装一个 PostgreSQL 服务器,比如this postgres APP(我选择这个的原因是您不必担心设置服务器)。
  • 将您的 Colab 连接到本地运行时
  • 通过%sql postgresql://username:@localhost:5432/username 访问服务器,其中用户名是您的系统用户名。根据 SQLAlchemy 所需的其他字段,只需“初始化”APP即可处理它们:密码已设置为无,主机设置为 localhost,端口 tp 5432 和 dbname 设置为系统用户名。

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 2019-11-11
    • 2017-10-07
    • 2011-04-06
    • 2023-03-14
    • 1970-01-01
    • 2019-03-16
    • 2020-12-16
    • 2018-12-07
    相关资源
    最近更新 更多