使用循环从未知列数的Python mysql显示内容

2024-05-23 21:16:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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]”


Tags: ofdebug内容readdatafunctionquerycursor
1条回答
网友
1楼 · 发布于 2024-05-23 21:16:54

可以使用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'))

相关问题 更多 >