简体   繁体   English

可以指定路径以在sqlalchemy上使用postgresql创建数据库吗?

[英]Can a path be specified to create a database using postgresql on sqlalchemy?

I'm currently trying to create a postgresql database using sqlalchemy and would like this database file to be created in an external hard drive. 我目前正在尝试使用sqlalchemy创建一个postgresql数据库,并希望在外部硬盘驱动器中创建此数据库文件。 I can do that using sqlite3 which can be done just be adding the path after the string that will go into the engine: 我可以使用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)

Which will then make the database file within the specified path. 然后它将使数据库文件位于指定的路径内。 On the other hand postgresql uses a different syntax for the engine: 另一方面,PostgreSQL对引擎使用了不同的语法:

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

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

as explained on this question or the documentation . 如此问题文档所述 However it is not clear for me if I can specify a path for this database file to be written like on the sqlite. 但是,对于我来说,是否可以指定要在sqlite上写入此数据库文件的路径,对我来说还不清楚。 When I created the database using the database string as: 当我使用数据库字符串创建数据库时:

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

for a mock database I couldn't find the database_name file inside the databasepath path. 对于模拟数据库,我在databasepath路径内找不到database_name文件。 Can I specify a path for the file to be created after all or they stay confined within the server created during postgresql installation? 我到底可以指定要创建的文件的路径,还是将它们限制在Postgresql安装期间创建的服务器中?

Thanks! 谢谢!

No, that's not possible. 不,那不可能。

Postgres stores the data for all databases of a cluster (aka "instance") inside a single directory which is specified during the creation of the Postgres instance (via initdb ). Postgres将群集的 所有数据库(也称为“实例”)的数据存储在单个目录中 ,该目录是在创建Postgres实例(通过initdb )期间指定的。

Additionally, you can't create a database by connecting to it. 此外,您无法通过连接来创建数据库。 You need to first run the create database command, only then you can connect to it. 您需要首先运行create database命令,然后才能连接到该数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM