我应该在代码中添加什么,以便打印在表格的哪一行是if exist == True :
的用户名?它也可以返回记录的id,因为它会显示它在表中的位置。我没有包含数据库代码,因为我认为没有必要。对不起我的错误解释英语不是我的母语。
engine = create_engine('sqlite:///sqlalchemy_login.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
username_attempt = raw_input('Enter username:')
username_attempt = unicode(username_attempt)
exist = session.query(exists().where(user.username == username_attempt)).scalar()
while exist == False :
print 'Incorrect username'
username_attempt = raw_input('Enter username:')
username_attempt = unicode(username_attempt)
exist = session.query(exists().where(user.username == username_attempt)).scalar()
答案 0 :(得分:1)
sqlalchemy支持select
语句查询。所以我会做类似的事情:
def _get_users(attempt):
stmt = sqlalchemy.select([users]).where(users.c.username == attempt)
return [dict(r) for r in sqlalchemy.execute(stmt)]
def _get_attempt():
username_attempt = raw_input('Enter username:')
return unicode(username_attempt)
attempt = _get_attempt()
recs = _get_users(attempt)
while not recs:
print 'Incorrect username'
attempt = _get_attempt()
recs = _get_users(attempt)
print recs
当recs不为空(并且已经给出了有效的用户名)时,recs将包含表示表中行的字典列表。您可以遍历recs
并获取每行的id
。
注意:您需要定义users
表:
db_metadata = sqlalchemy.MetaData()
users = sqlalchemy.Table('users', db_metadata,
Column('id', sqlalchemy.Integer, primary_key=True),
Column('username', sqlalchemy.Integer, primary_key=True),
# add rest of your table schema here...
)