Search code examples
mysql-pythongae-python27

Output python query output into string


Trying to use this syntax:

import MySQLdb as mdb
con = mdb.connect(host = 'host', user = 'user', passwd = 'pwd', db = 'db');
cur = con.cursor()
cur.execute('select distinct name from names');
rows = cur.fetchall()
print(rows)
(('1',), ('2',), ('3',), ('4',), ('5',))

I need to get this output to be in the format of a string so that I can include it as a variable in another query I'll be running in the same script.

'1','2','3','4','5'

I'm running this from command line and have tried a few things:

>>> for row in rows:
...   print "%s," % row
...

but unfortunately doesn't give me what I need.


Solution

  • rows = ('1',), ('2',), ('3',), ('4',), ('5',)
    output1=output2=""
    
    for row in rows:
        output1 += '\'' + str(row[0][0]) + '\'' + ','
        output2 += ' ' + str(row[0][0]) + ' ' + ','
    
    # To delete last char: ','
    output1 = output1[:-1]
    output2 = output2[:-1]
    
    print(rows)          # (('1',), ('2',), ('3',), ('4',), ('5',))
    print(output1)       # '1','2','3','4','5'
    print(output2)       #  1 , 2 , 3 , 4 , 5 
    

    output1 is what you expect, but you should probably feed output2 string to your script.