如何使用sqlalchemy从数据库中选择数据?

时间:2014-01-03 07:50:53

标签: sqlite sqlalchemy

我有两个sqlalchemy脚本,一个用于创建数据库和一些表,另一个用于从中选择数据。

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)

我可以运行 create_database.py 脚本,但是当我运行 select.py 脚本时,我收到以下错误

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

我可以通过将以下内容附加到 create_database.py

,从 create_database.py 中运行select语句
conn = engine.connect()
s = select([users])
result = conn.execute(s)

如何从单独的脚本运行select语句而不是 create_database.py

1 个答案:

答案 0 :(得分:2)

脚本select.py未在users中看到addressescreate_database.py。在使用它们之前将它们导入select.py

select.py

from create_database import users, addresses

## Do something with users and addresses