1👍
✅
You could try this:
# Build a comma-separated string of all items in list_project
data_list = ', '.join([item for item in list_project])
query = 'SELECT %s FROM proj_cpus WHERE project in (%s)'
# Supply the parameters in the form of a tuple
cursor.execute(query, (key, data_list))
cursor.fetchall()
will always return data in tuples like you have observed in comments, it is not because there is an issue with the query. To convert to json you could do something like the following (row_counter
is just a placeholder to make sure that there is a unique key for every entry).
import json
key = '*'
data_list = ', '.join([item for item in list_project])
query = 'SELECT %s FROM proj_cpus WHERE project in (%s)'
cursor.execute(query, (key, data_list))
all_rows = cursor.fetchall()
row_headings = [header[0] for header in cursor.description]
row_counter = 0
all_rows_container = {}
for item in all_rows:
item_dict = {row_headings[x]: item[x] for x in range(len(row_headings))}
all_rows_container[row_counter] = item_dict
row_counter += 1
json_data = json.dumps(all_rows_container)
print json_data
NOTE: the above may throw IndexError
if the query is not with key = '*'
because I think row_headings
will contain all of the schema for the table, even for values that you did not select in the query. However, it should be sufficient to demonstrate the approach and you can tailor it in the event that you pick specific columns only.
Source:stackexchange.com