3

I need help!! I have written a python code which queries the database and prints the result in the Linux shell prompt here is the code :

#!/usr/bin/python

import MySQLdb
import sys
import config
import csv     

db = MySQLdb.connect(config.host,config.user,config.password,config.dbname)
cursor=db.cursor()
print "Connected to the Mysql database"
cursor.execute("use " + config.dbname)

cursor.execute('SELECT DISTINCT LEARNER FROM EMS_data LIMIT 5')
result= cursor.fetchall()
print result

db.commit()
cursor.close()

This is what i get :

(("'Fang ",), ("'Nikhil '",), ("'Gavin '",), ("'Vamsi'",), ("'Shah'",))

How to remove these braces..?

1
  • You are returning a tuple of tuples; so use a loop to step through the tuple list and print each indiviual item. Commented Jun 10, 2013 at 11:25

2 Answers 2

6

The result returned by cursor.fetchall() is a tuple of tuples containing the fetched data. Each tuple represents a fetched row.

Because you are printing a tuple of tuples, you are seeing the braces. In order to display the data in a prefered format you'll have to iterate over the result and print each row accordingly.

The example below would print each row on a new line, and will separate the columns with a vertical bar:

for row in result:
    print " | ".join(row)
Sign up to request clarification or add additional context in comments.

1 Comment

it is expecting rows are strings and getting exception if it has int.
1

The result returned by cursor.fetchall() is a tuple of tuples containing the fetched data. Each tuple represents a fetched row.

1st line of code below will take tuples one by one.
2nd line will print not taken tuple itself, but exactly first element from it (without commas and brackets)

for row in result:
    print(row[0])

1 Comment

You can improve the quality of your answer by explaining what it does and how it solves the issue.

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.