【问题标题】:Can a path be specified to create a database using postgresql on sqlalchemy?可以指定路径以在 sqlalchemy 上使用 postgresql 创建数据库吗?
【发布时间】:2019-06-03 05:25:24
【问题描述】:

我目前正在尝试使用 sqlalchemy 创建一个 postgresql 数据库,并希望在外部硬盘驱动器中创建此数据库文件。我可以使用 sqlite3 做到这一点,只需在将进入引擎的字符串之后添加路径即可:

# To create the tables we need these packages
import sqlalchemy as sql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine 

# Creating the base.
Base = declarative_base()

# The tables would be defined here.

# Create an engine that stores data in the given directory.
path = '/path/'
engine = create_engine('sqlite:///'+path+'ARsdb.db')    

# Create all tables in the engine.
Base.metadata.create_all(engine)

这将使数据库文件在指定路径内。另一方面,postgresql 对引擎使用不同的语法:

# default
engine = create_engine('postgresql://user:pass@localhost/mydatabase')

# psycopg2
engine = create_engine('postgresql+psycopg2://user:pass@localhost/mydatabase')

如 question 或 documentation 中所述。但是,我不清楚我是否可以为这个数据库文件指定一个路径,就像在 sqlite 上一样。当我使用数据库字符串创建数据库时:

postgresql://user:password@localhost:5432/databasepath/database_name

对于模拟数据库,我在 databasepath 路径中找不到 database_name 文件。我是否可以为要创建的文件指定一个路径,或者它们仍然限制在安装 postgresql 期间创建的服务器中?

谢谢!

【问题讨论】:

    标签: python-3.x postgresql sqlite sqlalchemy


    【解决方案1】:

    不,这是不可能的。

    Postgres 将cluster(又名“实例”)的所有数据库的数据存储在single directory 中,该single directory 在创建Postgres 实例期间指定(通过initdb)。

    此外,您无法通过连接来创建数据库。您需要先运行create database 命令,然后才能连接到它。

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 2019-07-18
      • 2015-06-13
      • 2013-01-02
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      相关资源
      最近更新 更多