我正在尝试从数据库打印Python中的变量,以便它们在其自己的列中打印一个变量。我有以下内容:
import os,MySQLdb
db = MySQLdb.connect(read_default_file="/etc/my.cnf",read_default_group="mysql",db="Cinderella")
cursor = db.cursor()
sql = "select * from DatasetStatus"
try:
print '\n Mysql> ' + sql
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
name = row[0]
nused = row[1]
ndownloads = row[2]
incache = row[3]
entrydate = row[4]
size = row[5]
print "%n|%u|%d|%c|%e|%s"%\
(name|nused|ndownloads|incache|entrydate|size)
except:
print " Error ($s): unable to fetch data."%(sql)
db.close()
存储在不同行中的这六个值列表是我想要在列中打印的值。关于如何解决这个问题有什么建议吗?
最佳答案
您可以只执行 print '{}|{}|{}|{}|{}|{}'.format(*row)
而不必手动解压 row
如果您只需要使用它进行打印。
示例:
>>> row = ('hello', 'world', 'this', 'is', 'a', 'test')
>>> print '{}|{}|{}|{}|{}|{}'.format(*row)
hello|world|this|is|a|test
您将修改您的:
try:
print '\n Mysql> ' + sql
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print '{}|{}|{}|{}|{}|{}'.format(*row)
except:
print "Error ($s): unable to fetch data." % (sql)
关于python - 在不同列中打印数据库变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28242902/