大家好,我在Django中遇到此查询的问题
projects_name = str(kwargs['project_name']).split(',')
status = str(kwargs['status'])
list_project = tuple(projects_name)
opc_status = {'jobs_running':'running', 'jobs_pending':'pending', 'cpus_used':'cpu'}
if status in opc_status.values():
key = list(opc_status.keys())[list(opc_status.values()).index(status)] + ', entry_dt'
else:
key='*'
db = MySQLdb.connect(host='..', port=, user='..', passwd='..', db='..')
try:
cursor = db.cursor()
cursor.execute('SELECT %s FROM proj_cpus WHERE project in %s', key, list_project])
查询的第一个参数必须是*
或jobs_pending, entry_dt
但查询会返回此错误
tuple index out of range
有关如何正确创建查询的任何想法吗?
答案 0 :(得分:1)
你可以试试这个:
# 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()
将始终返回元组中的数据,就像您在评论中观察到的那样,并不是因为查询存在问题。要转换为json,您可以执行以下操作(row_counter
只是一个占位符,以确保每个条目都有唯一的键。)
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
注意:如果查询不在IndexError
,上面的内容可能会抛出key = '*'
,因为我认为row_headings
将包含该表的所有架构,即使对于您没有的值也是如此在查询中选择。但是,它应该足以证明该方法,并且您可以在仅选择特定列的情况下定制它。