如何使用mysql db通过django获取多行和多列

时间:2016-12-26 06:51:48

标签: python mysql django

获取代码下面的单行和单列是成功执行的。如何获得多个列和行?

  

views.py

def get_db_data(request):
    conn = MySQLdb.connect (host = "localhost", user = "test_user", passwd = "test_pwd", db = "myproject")
    cursor = conn.cursor ()
    cursor.execute ("SELECT email_address, mobile_number,id, city, state  FROM user")
    if cursor.rowcount == 0:
        html = "<html><body>There is no Faculty member with id %s.</body></html>" % email_address
    else:
        row = cursor.fetchone()
        html = "<html><body>E-Mail address %s.</body></html>" % row[0]
    return HttpResponse(html)

请帮助我。

3 个答案:

答案 0 :(得分:0)

UPD:

def get_db_data(request):
    conn = MySQLdb.connect (host = "localhost", user = "test_user", passwd = "test_pwd", db = "myproject")
    cursor = conn.cursor ()
    cursor.execute ("SELECT email_address, mobile_number,id, city, state  FROM user")
    if cursor.rowcount == 0:
        html = "<html><body>There is no Faculty member with id %s.</body> <html>" % email_address
    else:
        html = "<html>"
        for x in cursor.fetchone():
            html += "<body>E-Mail address %s.</body>" % x
        html += "<html>"
    return HttpResponse(html)

答案 1 :(得分:0)

所有列

cursor.execute("SELECT * FROM user")

所有行:

cursor.fetchall()

for row in cursor.fetchall():
    html = ...

还有一件事与你的问题无关,但在写if

时应该记住

对于if语句,值0, None, False都是false,因此最好先写if not cursor.rowcount if cursor.rowcount==0

答案 2 :(得分:0)

你可以使用它。

import MySQLdb
import MySQLdb.cursors

def get_db_data(request):
    conn = MySQLdb.connect(host="localhost", user="test_user", passwd="test_pwd", db="myproject", cursorclass=MySQLdb.cursors.DictCursor)
    cursor = conn.cursor()
    cursor.execute("SELECT email_address, mobile_number,id, city, state  FROM user")
    if cursor.rowcount == 0:
        html = "<html><body>There is no Faculty member with id.</body></html>"
    else:
        htm = "<html><body>"
        for row in cursor.fetchall():
            html += "Id - {id}, E-Mail address - {email_address}, Mobile Number - {mobile_number}, City - {city}, State {state}. </br>".format(**row)
        html += "</body></html>"
    return HttpResponse(html)