Creating a database
In SQLModel, connecting to a database is done via a SQLAlchemy engine. The engine is created by the create_engine()
method, imported from the SQLModel library.
The create_engine()
method takes the database URL as the argument. The database URL is in the form of sqlite:///database.db
or sqlite:///database.sqlite
. It also takes an optional argument, echo
, which when set to True
prints out the SQL commands carried out when an operation is executed.
However, the create_engine()
method alone isn’t sufficient to create a database file. To create the database file, the SQLModel.metadata.create_all(engine)
method whose argument is an instance of the create_engine()
method is invoked, such as the following:
database_file = "database.db" engine = create_engine(database_file, echo=True) SQLModel.metadata.create_all(engine)
The create_all()
method creates the database as well as the tables defined. It is important to note that the file containing...