python - (sqlite3.OperationalError)在Windows上的sqlalchemy中使用sqlite3连接字符串中的绝对文件路径时无法打开数据库文件
问题描述
我正在尝试使用 sqlite3 和 sqlalchemy 从连接字符串创建数据库引擎,但遇到了问题。
我的具体细节是我想在连接字符串中使用来自 os 模块的绝对文件路径(这使得我在任何地方只部署 python 时更容易)并且目前正在 Windows 上工作。
可以在此处找到此问题的最受关注的答案: OperationalError: (sqlite3.OperationalError) 无法打开数据库文件,但它的答案对我不起作用。
这是我当前的目录结构:
/db
-- assets.db
/app
-- load_engine.py
-- models.py
这个想法是我想从文件中的函数初始化我的 sqlalchemy 连接load_engine
,但将文件路径引用/db/assets.db
到其中。
这是里面的功能load_engine
:
def load_engine():
db_file = os.environ.get('database_file')
script_path = os.path.realpath('__file__')
parent_path = os.path.dirname(script_path)
db_path = os.path.join(os.path.sep,parent_path, "db", db_file)
engine = create_engine(fr"sqlite:///{db_path}")
return engine
我正在尝试通过models.py
以下方式在文件中调用此函数:
Base = declarative_base()
class Assets(Base):
"""Main table that will hold the list of ticker names"""
__tablename__ = 'assets'
id = Column(Integer, primary_key = True)
ticker = Column(String(250), nullable = False, unique = True)
type = Column(String(100), nullable = False)
class BarData(Base):
"""Will hold daily bar data from yahoo finance"""
__tablename__ = 'bardata'
id = Column(Integer, primary_key = True)
ticker = Column(String(250), ForeignKey("assets.ticker"), nullable = False)
open = Column(Float, nullable = False)
high = Column(Float, nullable = False)
low = Column(Float, nullable = False)
close = Column(Float, nullable = False)
volume = Column(Float, nullable = False)
dividends = Column(Float, nullable = False)
splits = Column(Float, nullable = True)
if __name__ == '__main__':
engine = load_engine()
Base.metadata.create_all(engine)
当我运行它时,我得到了错误,大概是因为我的文件路径错误。我已经尝试删除该assets.db
文件以查看它是否已更改,但它没有用。我还尝试使用 4 个正斜杠与 3 个,但也得到了相同的信息。
如果我引用同一目录中的文件,它工作正常,所以我认为问题是文件路径。
编辑:
根据评论,引擎的输出如下:
Engine(sqlite:////C:\Users\Jonat\trading\app\db\assets.db)