2017-02-27 66 views
0

我想在mysql查詢後導出一個csv文件。我得到以下錯誤;在Django上的Mysql錯誤

(1064,「您的SQL語法錯誤;檢查對應於你的MySQL服務器版本,在1號線附近使用‘’正確的語法手冊」)

import csv 

from django.db import connections 

from django.http import HttpResponse 

from django.views.generic import ListView 

from testing.models import TrRunSummary, TrDetails 


class ExportCsv(ListView): 
    """Displays the different tests performed on the specified test request""" 
    template_name = 'testing/tr_export_csv.html' 
    context_object_name = 'export_csv' 

    def get_context_data(self, **kwargs): 
     context = super(ExportCsv,self).get_context_data(**kwargs) 
     context['tr_info'] = self.tr_info() 

     return context 

    def get_queryset(self): 
     qtr_id = self.kwargs['trID'] 
     s = str(qtr_id) 
     print s 
     print type(s) 



cursor = connections['default'].cursor() 
    query ="SELECT results_stb_id, results_stbs.stb_id, stb_inv.mac_add, " 
    "test_functionality.test_functionality_code, test_cases.test_case_no, " 
    "SCRIPT.option_name AS script_result, POST.option_name AS post_result, " 
    "results_tests.started, results_tests.stopped, results_tests.test_duration, builds.baseline, " 
    "builds.build_type, stb_hw_info.stb_type, defects.defect_name, parser_output, log_url, " 
    "script_health_score, post_health_score FROM results_stbs " 
    "JOIN tr_test_cases " 
    "ON tr_test_cases.tr_test_case_id=results_stbs.tr_test_case_id " 
    "JOIN test_cases " 
    "ON test_cases.test_case_id=tr_test_cases.test_case_id " 
    "JOIN test_functionality " 
    "ON test_functionality.test_functionality_id=test_cases.test_functionality_id " 
    "LEFT JOIN stb_inv " 
    "ON results_stbs.stb_id=stb_inv.stb_id " 
    "LEFT JOIN result_options AS SCRIPT " 
    "ON results_stbs.script_result=SCRIPT.result_option_id " 
    "LEFT JOIN result_options AS POST " 
    "ON results_stbs.post_result=POST.result_option_id " 
    "JOIN results_tests " 
    "ON results_stbs.results_test_id=results_tests.results_test_id " 
    "JOIN builds " 
    "ON builds.build_id=results_stbs.build_id " 
    "JOIN stb_hw_info_ids " 
    "ON stb_hw_info_ids.stb_hw_info_ids_id=results_stbs.stb_hw_info_ids_id " 
    "JOIN stb_hw_info " 
    "ON stb_hw_info.stb_hw_info_id=stb_hw_info_ids.stb_hw_info_id " 
    "LEFT JOIN defects_tests " 
    "ON results_tests.results_test_id=defects_tests.results_test_id " 
    "LEFT JOIN defects " 
    "ON defects.defect_id=defects_tests.defect_id " 
    "WHERE tr_test_cases.tr_id = '%s' AND script_result IN (1, 3, 8) " 
    "OR tr_test_cases.tr_id = '%s' AND post_result IN (1, 3, 8) " 
    "ORDER BY results_stb_id ASC " % (s, s) 


     cursor.execute(query) 

     print cursor 



    def tr_info(self): 
     tr_id = self.kwargs['trID'] 
     tr_info = TrDetails.objects.get(
      tr_id=tr_id, 
     ) 
     return tr_info 



class SavedCsvView(ExportCsv): 
    """ 
    Subclass of above view, to produce a csv file 
    """ 
    template_name = 'TR_Export.csv' 
    content_type = 'text/csv' 

我的查詢在Python腳本上工作正常。當我添加Django視圖時,它給我錯誤。任何幫助將不勝感激。

+0

請貼全追蹤誤差 –

+0

你可以用這種方式https://docs.djangoproject.com/en/1.10執行直接的SQL查詢/ topics/db/sql /#executable-custom-sql-directly –

+3

用'\'結束帶有字符串的行或使用三重引號或用'()'圍繞'='後面的所有內容創建一個多行串。你是如何做到的,只有第一部分進入了字符串。 –

回答

0

如在評論中指出通過克勞斯d

終止與絃線與or use triple quotation marks or surround everything after the=用()來創建一個 多行字符串。你如何做到這一點只有第一部分進入 字符串。 - Klaus D.

您應該使用<tripple quotes> """<query>"""修復查詢字符串。

def get_queryset(self): 
    ... 
    query = """SELECT results_stb_id, results_stbs.stb_id, stb_inv.mac_add, 
     test_functionality.test_functionality_code, test_cases.test_case_no, 
     SCRIPT.option_name AS script_result, POST.option_name AS post_result, 
    ...""" 
    cursor.execute(query) 
    row = cursor.fetchall() 
    return row 

如何從數據庫直接SQL查詢返回的查詢響應光標,參考文檔:https://docs.djangoproject.com/en/1.10/topics/db/sql/#executing-custom-sql-directly

和這個例子:http://blog.appliedinformaticsinc.com/how-to-perform-raw-sql-queries-in-django/

OP添加了註釋的另一問題

Hi @KlausD。感謝您的幫助。圓括號幫助我解決 問題。那麼,我該如何運行這個查詢來導出csv文件?非常感謝 :)

要導出查詢響應爲csv,可以有多種選擇:

一種是直線前進的Django方法[參考] https://docs.djangoproject.com/en/1.10/howto/outputting-csv/

另一種是使用這個庫https://pypi.python.org/pypi/django-queryset-csv/

這是非常簡單的使用

from djqscsv import render_to_csv_response 

def csv_view(request): 
    qs = Foo.objects.filter(bar=True).values('id', 'bar') 
    return render_to_csv_response(qs) 
如果你想只寫CSV使用

這樣的:

from djqscsv import write_csv 

qs = Foo.objects.filter(bar=True).values('id', 'bar') 
with open('foo.csv', 'w') as csv_file: 
    write_csv(qs, csv_file)