# 返回列名 def query(sql): try: conn = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWORD, db=DATABASE, port=PORT, charset='utf8') cur = conn.cursor() cur.execute(sql) rows = cur.fetchall() index = cur.description result = [] for res in rows: row = {} for i in range(len(index) - 1): row[index[i][0]] = res[i] result.append(row) # conn.commit() # 這個對於增刪改是必須的,不然事務沒提交執行不成功 cur.close() conn.close() return result except MySQLdb.Error as e: print(e)