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 = cursor.fetchone()
    return render(request, "linechart.html")

It's giving output like below:

('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'))

expecting output:

 ["Sep", "7.00", "3.90", "-0.20", "-0.90"],["Oct", "6.90", "4.20", "0.80", "0.60"]

How can i achieve this. please help me with this.

5 Answers 5

2

According to this link http://mysql-python.sourceforge.net/MySQLdb.html fetchone() returns a tuple.

To convert that to a list, simply cast it.

row = list(cursor.fetchone())

You can then iterate the list to get them in the proper format you are seeking.

Sign up to request clarification or add additional context in comments.

Comments

1

Blindly converting everything to strings (because you haven't been specific):

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")

I'm not sure this solves your problem. Do you want all the Decimal converted to strings? Some kind of floating point number is probably more useful for charting.

2 Comments

each row seperate with comma. how to do that?
Try print(rows). Is that what you want?
1

Your question isn't 100% clear but if you're really just trying to get a list of strings:

>>> 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']

Comments

1

Try this:-

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")

Comments

1

please try

row = cursor.dictfetchall() #which gives dict

row = cursor.fetchall() #gives a list.

Output :-

["Sep", "7.00", "3.90", "-0.20", "-0.90"],["Oct", "6.90", "4.20", "0.80", "0.60"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.