Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting brackets while executing query into mysql database using python

Tags:

python

mysql

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..?

like image 725
user2470026 Avatar asked Nov 16 '25 10:11

user2470026


1 Answers

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)
like image 173
Ion Scerbatiuc Avatar answered Nov 19 '25 00:11

Ion Scerbatiuc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!