7

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?

2 Answers 2

3
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
Sign up to request clarification or add additional context in comments.

1 Comment

Although this code might be an answer to the question, it would be more helpful to future readers if an explanation was added.
0

ATTACH is your friend.

You can attach an in-memory database to the current database session.

E.g.,

db.init('sqlite://')
db.execute("ATTACH DATABASE ':memory:' AS my_database")
db.create_all()

3 Comments

I'm sorry but I can't figure out how to use your answer within my code
In order to use :memory: you need to specify an empty url for your db. db = create_engine('sqlite://'). Your code: engine = create_engine('sqlite:///:memory:') is wrong. Look here
@MarcoMilanesio, the syntax is wrong, the correct syntax for ATTACH is ATTACH DATABASE ':memory:' AS my_database;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.