python - 在不同列中打印数据库变量

标签 python mysql sql database

我正在尝试从数据库打印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/

相关文章:

php - 选择带有运算符 php 名​​称的行

sql - 无法在子查询的 where 子句中引用聚合函数的别名

python - 使用 pip 有条件地安装 wheel 文件

Mysql检查约束不起作用

python - 从数据中删除序列 Pandas Python Numpy

php - 产品搜索 php mysql

php - undefined index 错误 - 图片上传相同的代码正在处理另一个示例

c# - 从 Expression<Func<T, T>> 生成动态更新命令

python - 如何使用 BeautifulSoup4 将 <br> 标记之前的所有文本获取到 pandas 数据框中

python - 使用 matplotlib 在网格中显示值