SQL Connection Strings

· by

Contents

When you want to connect to a database in SQLAlchemy, you need a connection string. It usually has the form

dialect[+driver]://user:password@host/dbname[?key=value..]

Quite often, the user is root and the host is localhost.

Once you have the valid connection string, you can test if it works via this script:

import sqlalchemy

engine = sqlalchemy.create_engine(SQLALCHEMY_DATABASE_URI, echo=True)
print(engine.table_names())

SQLite

requirements.txt: None

Connection:

SQLALCHEMY_DATABASE_URI = "sqlite:///absolute_filepath"

# Example:
SQLALCHEMY_DATABASE_URI = "sqlite:////tmp/test.db"

The first two slashes come from the separator after the dialect (://), the third one separates the (empty) host from the database name, and the fourth one is the beginning of the absolute path to the database file.

If you want an in-memory SQLite DB, just specify an empty URL (source):

SQLALCHEMY_DATABASE_URI = "sqlite://"

MySQL and MariaDB

requirements.txt:

PyMySQL

Connection:

SQLALCHEMY_DATABASE_URI = "mysql+pymysql://user:password@host/dbname"

There are a lot of other MySQL drivers:

Others

I haven't tried them, but SQLAlchemy lists more like Oracle, Microsoft SQL Server and Sybase.