我对Python或SQL不太熟悉,并且受命创建一个搜索结果页面以显示SQL数据库中的用户信息。我正在使用flask,将JSON对象从python后端发送到javascript / jquery前端。当一个搜索(通过电子邮件地址进行搜索)返回的用户只有一个使用以下代码时,我设法显示了一个用户:
user = db.execute(
'SELECT * FROM user WHERE email = ?', (emailInput,)
).fetchone()
if user is None:
user_details = {
'first' : 'error'
}
y = json.dumps(user_details)
return jsonify(y)
if user['first'] is None:
first = ""
else:
first = user['first']
if user['email'] is None:
email = ""
else:
email = user['email']
if user['last'] is None:
last = ""
else:
last = user['last']
if user['address_line1'] is None:
address_line1 = ""
else:
address_line1 = user['address_line1']
if user['address_line2'] is None:
address_line2 = ""
else:
address_line2 = user['address_line2']
if user['username'] is None:
username = ""
else:
username = user['username']
user_details = {
'first': first,
'last': last,
'email': email,
'address1': address_line1,
'address2': address_line2,
'username': username
}
y = json.dumps(user_details)
return jsonify(y)
现在,我想使用fetchall()升级此代码,以返回通过SQL调用获取的每个用户的user_details,但我不知道该怎么做。预先感谢您的帮助。
编辑: 我真正需要帮助的是将多个结构变成这样:
user_details = {
'first': first,
'last': last,
'email': email,
'address1': address_line1,
'address2': address_line2,
'username': username
}
变成这样的一个大结构:
users = {
user_details1 = {
'first': first,
'last': last,
'email': email,
'address1': address_line1,
'address2': address_line2,
'username': username
}
user_details2 = {
'first': first,
'last': last,
'email': email,
'address1': address_line1,
'address2': address_line2,
'username': username
}
etc.
}
答案 0 :(得分:0)
不用花几个小时来解决这个特定的SQL问题,而是花几个小时来学习an ORM like sqlalchemy,这样您就不必再写SQL了:)
答案 1 :(得分:0)
fetchall
返回一个列表列表,因此您只需要遍历外部列表(表的行)。例如:
users = db.execute(
'SELECT * FROM user WHERE email = ?', (emailInput,)
).fetchall()
for user in users:
if user['first'] is None:
<etc>