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

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


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

from sqlalchemy import create_engine, ForeignKeyfrom sqlalchemy import Column, Date, Integer, Stringfrom sqlalchemy.ext.declarative import declarative_baseengine = 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)


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:

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)


As others have posted, SQLAlchemy will do this automatically. I encountered this error, however, when I didn't use enough slashes!

I used SQLALCHEMY_DATABASE_URI="sqlite:///path/to/file.db" when I should have used four slashes: SQLALCHEMY_DATABASE_URI="sqlite:////path/to/file.db"