4 回答

TA贡献1828条经验 获得超3个赞
import pymysql
cur = mysql.connect().cursor(pymysql.cursors.DictCursor)
cur.execute(sql)
row = cur.fetchall()
print row
[{u'symbol': u'AAPL'}, {u'symbol': u'SQ'}]

TA贡献1775条经验 获得超11个赞
问题没有指定您的 SQL 适配器,但如果您将 SQLAlchemy 与 Flask 一起使用,以下是如何查询数据库并以所需格式输出结果的示例:
from flask import Flask
from models import db
import json
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'your_database_connection_string'
db.init_app(app)
result = db.session.execute("SELECT * FROM categories WHERE id = :id", {"id":999})
# If no rows were returned (e.g., an UPDATE or DELETE), return an empty list
if result.returns_rows == False:
response = []
# Convert the response to a plain list of dicts
else:
response = [dict(row.items()) for row in result]
# Output the query result as JSON
print(json.dumps(response))

TA贡献2080条经验 获得超4个赞
我找到了使用 sql-alchemy 更好的方法的解决方案。如果想要按照问题陈述的解决方案,那么这里是一个解决方案
import json
def conv_func(list_data):
dic ={ "CATEGORY_ID":list_data[0],
"CATEGORY_NAME":list_data[1],
"DESCRIPTION":list_data[2]
}
return dic
data = '''[[
1,
"FURNITURE",
"INDOOR FURNITURE"
],
[
2,
"AUTOMOBILES",
"CARS, BIKES"
],
[
3,
"LAPTOP & ACCESSORIES",
"LAPTOP, MOUSE, KEY BOARD, PENDRIVE"
]
]'''
data = json.loads(data)
new_data=[]
for i in data:
new_data.append(conv_func(i))
print(new_data)
添加回答
举报