SQLAlchemy Core Python


This entry is part 2 of 3 in the series SQLAlchemy

I will jump right into a simple example using Jupyter Notebook with Anaconda Navigator. Here we have a Python project that is connecting to a SQLite database using the ORM SQLAlchemy.

import sqlalchemy as sa
sqlalchemy.__version__
'1.4.39'
engine = sa.create_engine('sqlite:///emp.db')
connection = engine.connect()

meta_data = sa.MetaData()

employees = sa.Table(
    'Employees', meta_data,
    sa.Column('id', sa.Integer(), primary_key=True),
    sa.Column('name', sa.String()),
    sa.Column('position', sa.String())
)
meta_data.create_all(engine)

The database is created in the current directory. What is the current directory? Because I am using Anaconda Navigator in Windows here, the current directory is where the project is stored, which is C:\users\username where username is the Windows user. This below is what it looks like in DB Browser.

Here is the syntax if you want to specify a location in Windows. By the way, single quotes also work.

engine = sa.create_engine(r"sqlite:///D:\Test\emp2.db") 

print(employees.insert())
INSERT INTO "Employees" (id, name, position) VALUES (:id, :name, :position)
Series Navigation<< What is SQLAlchemy?SQLAlchemy Core Insert >>

Leave a Reply