使用Python检索MySQL数据

时间:2014-03-25 01:32:04

标签: python mysql django

来自MySQL的数据正在显示不应该存在的额外字符。我使用的是Python 2.7和Django。

我试图搜索如何解决此问题,但我甚至不知道该怎么称呼这个问题。

这是数据显示的方式:(' Royal Ashburn',)用于CharField或(5L,)用于IntegerField(应该只显示5)

我有一种感觉这与Json或其他某种效果有关,但我不确定(我还是很新)有没有办法解决这个问题?

View.py

def getCourses(request):

db = MySQLdb.connect(host="localhost", user="***", passwd="***", db="golf")
cur = db.cursor()
cur.execute("SELECT course_name FROM golfapp_golfcourses")
data = cur.fetchall()

"""cur.close()
connection.close()
sys.exit()"""

return render_to_response('DBTest.html', {'data':data})

course.html

{% include "base.html" %}
<html>
<body>

<select name="list_courses">
{% for data in data %}
 <option>{{ data }} </option>
{% endfor %}
</select>


</body>
</html>

修改 根据回答评论: Views.py

def GetAllCourses(request):
    db = MySQLdb.connect(host="localhost", user="edwardb", passwd="edwards17",         db="golfapp")
    cur = db.cursor()
    cur.execute("SELECT course_name, par_front_9, par_back_9, total_par FROM     golfapp_golfcourses")
    data1 = [course_name for (course_name,) in cur.fetchall()]
    data2 = [par_front_9 for (par_front_9,) in cur.fetchall()]
    data3 = [par_back_9 for (par_back_9,) in cur.fetchall()]
    data4 = [total_par for (total_par,) in cur.fetchall()]

"""cur.close()
connection.close()
sys.exit()"""

    return render_to_response('golfcourses.html', {'data1':data1}, {'data2':data2}, {'data3':data3}, {'data4':data4},)

模板:

{% extends "base.html" %}

{% block content %}

<table style="margin-left:15%" class="table table-bordered">
  <tbody>
  <th>
    <td>Golf Course</td>
    <td>Front 9</td>
    <td>Back 9</td>
    <td>Total Par</td>
  </th>

  <tr>
    {% for data1 in data1 %}
    <td>{{ data1 }} </td>
    {% endfor %}
    {% for data2 in data2 %}
    <td>{{ data1 }} </td>
    {% endfor %}
    {% for data3 in data3 %}
    <td>{{ data3 }} </td>
    {% endfor %}
    {% for data4 in data4 %}
    <td>{{ data4 }} </td>
    {% endfor %}
  </tr>
 </tbody

</table>
</div>
 {% endblock %}

1 个答案:

答案 0 :(得分:1)

fetchall()为每行返回列的元组。即使您请求了一个列,data中的每一行仍然是一个元组,只是一个元素。你想要:

data = [course_name for (course_name,) in cur.fetchall()]

编辑:要渲染多个列,您不需要清理&#34;在所有:

data = cur.fetchall()

您只需访问模板中的每一列:

{% for course_name, par_front_9, par_back_9, total_par in data %}
<tr>
  <td>{{ course_name }}</td>
  <td>{{ par_front_9 }}</td>
  <td>{{ par_back_9 }}</td>
  <td>{{ total_par }}</td>
</tr>
{% endfor %}