【问题标题】:Python mysql show content from unknown number of columns with loopPython mysql用循环显示来自未知数量的列的内容
【发布时间】:2018-07-31 10:23:10
【问题描述】:

我有一个 MySQL 表,其中有许多行,我不知道。 我设法使用这个函数显示了前 3 行的内容:

def read_some_data():
   read_query_bis = """SELECT * FROM """ + table_name + " ;"
   cursor.execute(read_query_bis)
   rows = cursor.fetchall()
   print("*** DEBUG FUNCTION Read",cursor.rowcount,"row(s) of data.")
   # Print first 3 columns of all rows
   for row in rows:
       print("*** DEBUG FUNCTION Data row = (%s, %s, %s)" %(str(row[0]), str(row[1]), str(row[2])))

列数未知,有没有办法使用 fetchall 和循环来获取所有行和所有列而不是给定数字(在我的示例中,所有行为 3)?

编辑:至于下面的 Remarque,我可以添加类似的内容:

Rows_var_placeholders = ", ".join(["%s"] * Rows_Lengh) 

哪朵云给了我:

%s, %s, %s, %s, %s, %s 

我可以使用,但我的问题更多的是“str(row[0]”

【问题讨论】:

  • 试试len(row)?
  • 是的,我虽然是这样,但我确实想做循环,比如:“for i in len(row) print”,因为它会按顺序显示,我不想要.
  • 我可以做一些事情 "Rows_var_placeholders = ", ".join(["%s"] * Rows_Lengh)" 得到 (%s, %s, %s, %s, %s, % s) 但我应该如何处理“str(row[i])”?

标签: python mysql loops


【解决方案1】:

您可以使用cursor.description 访问返回的列。

在下面的示例中,我为每列构建了带有占位符的调试字符串,并使用了较新的 .format() 方法,因为它允许元组扩展。

def read_some_data():
    read_query_bis = """SELECT * FROM """ + table_name + " ;"
    cursor.execute(read_query_bis)
    rows = cursor.fetchall()
    print("*** DEBUG FUNCTION Read",cursor.rowcount,"row(s) of data.")
    for row in rows:
        # Create a placeholder for each column
        placeholder = ','.join(['{:s}']*len(cursor.description))
        # Map each col tuple to a str
        items = [str(v) for v in cursor.description]
        # Add the placeholder to the debug string
        debug_str = "*** DEBUG FUNCTION Data row = ({:s})".format(placeholder)
        # Print the debug string with the expanded list of column tuples
        print(debug_str.format(*items))

这是我测试过的一个例子:

desc = [('col1', 'a'), ('col2', 'b'), ('col3', 'c'), ('col4', 'd')]
placeholder = ','.join(['{:s}']*len(desc))
items = [str(v) for v in desc]
debug_str = "*** DEBUG FUNCTION Data row = ({:s})".format(placeholder)
print(debug_str.format(*items))

输出:

*** DEBUG FUNCTION Data row = (('col1', 'a'),('col2', 'b'),('col3', 'c'),('col4', 'd'))

【讨论】:

  • 谢谢!我拿了它 !标记为已回答并为您的回答点赞!
猜你喜欢
  • 2017-03-26
  • 2021-03-31
  • 2011-08-27
  • 2015-12-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 2019-02-04
  • 1970-01-01
相关资源
最近更新 更多