Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python SQLAlchemy in-memory database connect

I'm creating a in-memory database with python and I want to use SQLAlchemy with it.

All my application is currently working directly with queries to the db.

I've seen multiple ways of connecting but none of it is working. My current attempt stands as:

# Creates an sqlite database in memory
db = Database(filename=':memory:', schema='schema.sql')
db.recreate()

# ORM
engine = create_engine('sqlite:///:memory:')

Base = automap_base()
Base.prepare(engine, reflect=True)
User = Base.classes.user

session = Session(engine)

This gives AttributeError: user. How do I properly connect my database to the SQLAlchemy?

like image 602
walkman Avatar asked Aug 12 '26 15:08

walkman


1 Answers

from sqlalchemy import create_engine   
from sqlalchemy.orm import registry, Session
 
engine = create_engine("sqlite+pysqlite:///:memory:", echo=True, future=True)
session = Session(engine)
registry().metadata.create_all(engine)

:memory: is a special name used by sqlite for an in-memory database (see here).

sqlite+pysqlite is the database and driver. The format of the connection string is

dialect+driver://username:password@host:port/database
like image 113
glisu Avatar answered Aug 14 '26 12:08

glisu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!