Python mysql使用循环显示未知数量列中的内容
我有一个MySQL表,其中有许多我不知道的行。 我使用此函数显示了前3行的内容:Python mysql使用循环显示未知数量列中的内容,python,mysql,loops,Python,Mysql,Loops,我有一个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 da
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
编辑:对于下面的评论,我可以添加如下内容:
Rows_var_placeholders = ", ".join(["%s"] * Rows_Lengh)
哪朵云给了我:
%s, %s, %s, %s, %s, %s
我可以使用,但我的问题更多的是strow[0]您可以使用访问返回的列
在下面的示例中,我为每列构建了带有占位符的调试字符串,并使用了更新的方法,因为它允许元组扩展
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'))
尝试lenrow?是的,我想这样做,但我确实不想做循环:因为我在lenrow打印,因为它会以顺序的方式显示,这是我不想要的。我可以做一些Rows\u var\u placeholders=,。加入[%s]*Rows\u Lengh以获得%s,%s,%s,%s,%s,%s,但是我应该如何继续执行strrow[i]?谢谢!我接受了!标记为已回答,并对您的答案进行投票!