Search code examples
pythonsqlitesqlalchemy

Creating SQLite database if it doesn't exist


I am trying out SQLAlchemy and I am using this connection string:

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

Does SQLAlchemy create an SQLite database if one is not already present in a directory it was supposed to fetch the database file?


Solution

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

    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)