Postgresql 如何从Google Colab连接Postgres数据库?

Postgresql 如何从Google Colab连接Postgres数据库?,postgresql,google-colaboratory,Postgresql,Google Colaboratory,我可以通过上传数据库文件并执行以下命令从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中上传数据库文件,因为它的性质。对于博士后来说,情况并不那

我可以通过上传数据库文件并执行以下命令从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中上传数据库文件,因为它的性质。对于博士后来说,情况并不那么清楚,至少我不知道该怎么做。我已检查并实施如下:

%sql postgres://postgres:1234@postgres/postgres
但它没有起作用。错误消息:

Connection info needed in SQLAlchemy format, example:
           postgresql://username:password@hostname/dbname
           or an existing connection: dict_keys([])
OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
我也试过这个:

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')
错误消息:

Connection info needed in SQLAlchemy format, example:
           postgresql://username:password@hostname/dbname
           or an existing connection: dict_keys([])
OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?

我找不到解决办法。谢谢你的帮助

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

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

  • 例如,在本地安装PostgreSQL server(我选择此选项的原因是您不必担心服务器的设置)
  • 将Colab连接到本地运行时
  • 通过
    %sql p访问服务器ostgresql://username:@localhost:5432/username
    其中username是您的系统用户名。根据SQLAlchemy所需的其他字段,只需“初始化”应用程序即可处理这些字段:密码已设置为无、主机到本地主机、端口tp 5432和数据库名到系统用户名

SQLite3只是一个在内存中运行的库,可以在任何需要的地方运行。这就是它的美妙之处。但是PostgreSQL必须安装在某个地方,您将使用适当的IP连接到它。再看看这个