def index(request):
conn = MySQLdb.connect(host="localhost", user="user", passwd="pwd", db="highchart_with_django")
cursor = conn.cursor()
cursor.execute("SELECT categories,tokyo,london,new_york,berlin FROM basic_line_chart")
row = cursor.fetchone()
while row is not None:
print row
row = cursor.fetchone()
return render(request, "linechart.html")
它提供如下输出:
('Sep', Decimal('7.00'), Decimal('3.90'), Decimal('-0.20'), Decimal('-0.90'))
('Oct', Decimal('6.90'), Decimal('4.20'), Decimal('0.80'), Decimal('0.60'))
期待输出:
["Sep", "7.00", "3.90", "-0.20", "-0.90"],["Oct", "6.90", "4.20", "0.80", "0.60"]
我怎样才能做到这一点。请帮帮我。
答案 0 :(得分:2)
根据此链接http://mysql-python.sourceforge.net/MySQLdb.html fetchone()
会返回一个元组。
要将其转换为列表,只需将其转换为。
row = list(cursor.fetchone())
然后,您可以迭代列表,以便以您正在寻找的正确格式获取它们。
答案 1 :(得分:1)
盲目地将所有内容转换为字符串(因为您没有具体说明):
def index(request):
conn = MySQLdb.connect(host="localhost", user="user", passwd="pwd", db="highchart_with_django")
cursor = conn.cursor()
cursor.execute("SELECT categories,tokyo,london,new_york,berlin FROM basic_line_chart")
rows = [[str(field) for field in row] for row in cursor]
for row in rows:
print(row)
return render(request, "linechart.html")
我不确定这会解决你的问题。您希望所有Decimal
转换为字符串吗?某种浮点数可能对图表更有用。
答案 2 :(得分:1)
您的问题并非100%明确,但如果您真的只是想获取字符串列表:
>>> for row in cursor.fetchall():
... print [str(col) for col in row]
...
['Sep', '7.00', '3.90', '-0.20', '-0.90']
['Oct', '6.90', '4.20', '0.80', '0.60']
答案 3 :(得分:1)
请尝试
row = cursor.dictfetchall()
#which给dict
row = cursor.fetchall()
#给出一个列表。
输出: -
["Sep", "7.00", "3.90", "-0.20", "-0.90"],["Oct", "6.90", "4.20", "0.80", "0.60"]
答案 4 :(得分:1)
试试这个: -
def index(request):
conn = MySQLdb.connect(host="localhost", user="user", passwd="pwd", db="highchart_with_django")
cursor = conn.cursor()
cursor.execute("SELECT categories,tokyo,london,new_york,berlin FROM basic_line_chart")
row = cursor.fetchone()
while row is not None:
print row
row = list(cursor.fetchone())
return render(request, "linechart.html")