2

I am using PyMySQL to perform select queries from a DB and I wanted to use tabulate to format the output of those queries. I have been able to get tabulate to work correctly when the SQL query involves only selecting one column, but I can't get tabulate to work with queries that involve selecting multiple columns.

I have tried the following:

  • explicitly naming the headers by doing headers=['column name 1', 'column name 2'...]
  • telling tabulate to use the keys from the dictionary that PyMySQL produces (I am using the DictCursor and I can verify that the output is a proper dictionary by doing 'type(result)'
displayConfigSummary = "select `Product Line`.`Product Line Name`, `Product Configuration`.`Processor`, `Product Configuration`.`Graphics Card`, `Product Configuration`.`Memory Capacity (GB)`, `Product Configuration`.`Storage Capacity (GB)`  from `Product Line`,`Product Configuration` where `Product Configuration`.`Product Line ID` = `Product Line`.`GUID` and `Product Configuration`.`SKU ID` = %s"

cursor.execute(displayConfigSummary,(configID))

result = cursor.fetchone()

print('Here is your completed configuration:\n')

print(tabulate(result, headers='keys', tablefmt='psql'))

When I debug the program, I get the error -: Exception has occurred: TypeError zip_longest argument #4 must support iteration

Kalana
  • 5,631
  • 7
  • 30
  • 51

1 Answers1

0

I found that the solution to this problem ended up being that I should use cursor.fetchall() instead of cursor.fetchone(). Even though the SQL query would only produce one row, by using the fetchall() method, I am able to get tabulate to recognize the column names and print them out.

displayConfigSummary = "select `Product Line`.`Product Line Name`, `Product Configuration`.`Processor`, `Product Configuration`.`Graphics Card`, `Product Configuration`.`Memory Capacity (GB)`, `Product Configuration`.`Storage Capacity (GB)`  from `Product Line`,`Product Configuration` where `Product Configuration`.`Product Line ID` = `Product Line`.`GUID` and `Product Configuration`.`SKU ID` = %s"

cursor.execute(displayConfigSummary,(configID))

result = cursor.fetchall()

print('Here is your completed configuration:\n')

print(tabulate(result, headers='keys' ,tablefmt='psql'))