0

I have two sqlalchemy scripts, one that creates a database and a few tables and another that selects data from them.

create_database.py

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey, select
engine = create_engine('sqlite:///test.db', echo=True)
metadata = MetaData()

addresses = Table ('addresses', metadata,
    Column('id', Integer, primary_key=True),
    Column('user_id', None, ForeignKey('users.id')),
    Column('email_addresses', String, nullable=False)
)

users = Table ('users', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String),
    Column('fullname', String),
)

metadata.create_all(engine)

select.py

from sqlalchemy import create_engine, select
engine = create_engine('sqlite:///test.db', echo=True)

conn = engine.connect()
s = select([users])
result = conn.execute(s)

I am able to run the create_database.py script but when I run the select.py script I get the following error

$ python select.py
Traceback (most recent call last):
  File "select.py", line 5, in <module>
    s = select([users])

I am able to run the select statement from within the create_database.py by appending the following to create_database.py

conn = engine.connect()
s = select([users])
result = conn.execute(s)

How can I run the select statements from a separate script than create_database.py

1 Answer 1

2

The script select.py does not see users and addresses defined in create_database.py. Import them in select.py before using them.

In select.py:

from create_database import users, addresses

## Do something with users and addresses
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.