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

Question:

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

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?.

Asked By: Gandalf

||

Answers:

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)
Answered By: Gandalf

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)
Answered By: danio

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"

Answered By: dsummersl

Linux stored SQLite3 database

database will be create in the same folder as the .py file:

engine = create_engine('sqlite:///school.db', echo=True)

will instantiate the school.db file in the same folder as the .py file.

Answered By: Arthur Zennig

@Gandolf’s answer was good.

The database is created it when you make any connection with your engine.

Here’s an example of doing nothing with a database besides connecting to it, and this will create the database.

from sqlalchemy import create_engine

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

with engine.connect() as conn:
    pass

Without the engine.connect() or some form of metadata.create_all() the database will not be ceated.

Answered By: Zack Plauché
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.