0

尝试使用此语法:

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

我需要让这个输出采用字符串的格式,以便我可以将它作为变量包含在另一个查询中,我将在同一个脚本中运行。

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

我从命令行运行它并尝试了一些事情:

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

但不幸的是并没有给我我需要的东西。

4

1 回答 1

1
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 是您所期望的,但您可能应该将 output2 字符串提供给您的脚本。

于 2019-08-15T21:07:14.747 回答