Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 688
Gandalf Avatar asked Apr 29 '13 17:04

Gandalf


People also ask

Can SQLAlchemy create database?

Creating and Inserting Data into TablesBy passing the database which is not present, to the engine then sqlalchemy automatically creates a new database.

Does SQLAlchemy work with SQLite?

The great thing about SQLAlchemy is that it supports all popular database systems, including SQLite3, MySQL, PostgreSQL, Oracle, Microsoft SQL Server, etc.

What is the difference between SQLite and SQLAlchemy?

Sqlite is a database storage engine, which can be better compared with things such as MySQL, PostgreSQL, Oracle, MSSQL, etc. It is used to store and retrieve structured data from files. SQLAlchemy is a Python library that provides an object relational mapper (ORM).


2 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) 
like image 153
Gandalf Avatar answered Sep 16 '22 14:09

Gandalf


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"

like image 30
dsummersl Avatar answered Sep 18 '22 14:09

dsummersl