Python sqlalchemy,如果不存在则创建一个sqlite数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16284537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:12:29  来源:igfitidea点击:

sqlalchemy,creating an sqlite database if it doesn't exist

pythonsqlsqlitesqlalchemy

提问by Gandalf

I am trying out sqlalchemy and i am using this connection string to connect to my databases

我正在尝试 sqlalchemy 并且我正在使用此连接字符串连接到我的数据库

engine = create_engine('sqlite:///C:\sqlitedbs\database.db')

Does sqlalchemy create an sqlite database for you if one is not already present in a directory it was supposed to fetch the database file?.

sqlalchemy 是否会为您创建一个 sqlite 数据库,如果它不存在于它应该获取数据库文件的目录中?。

采纳答案by Gandalf

Yes,sqlalchemy does create a database for you.I confirmed it on windows using this code

是的,sqlalchemy 确实为您创建了一个数据库。我使用此代码在 Windows 上确认了它

from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///C:\sqlitedbs\school.db', echo=True)
Base = declarative_base()


class School(Base):

    __tablename__ = "woot"

    id = Column(Integer, primary_key=True)
    name = Column(String)  


    def __init__(self, name):

        self.name = name    


Base.metadata.create_all(engine)

回答by danio

I found (using sqlite+pysqlite) that if the directory exists, it will create it, but if the directory does not exist it throws an exception:

我发现(使用 sqlite+pysqlite)如果目录存在,它会创建它,但如果目录不存在,它会抛出异常:

OperationalError: (sqlite3.OperationalError) unable to open database file

My workaround is to do this, although it feels nasty:

我的解决方法是这样做,虽然感觉很讨厌:

    if connection_string.startswith('sqlite'):
        db_file = re.sub("sqlite.*:///", "", connection_string)
        os.makedirs(os.path.dirname(db_file), exist_ok=True)
    self.engine = sqlalchemy.create_engine(connection_string)