2017-01-04 90 views
2

我試圖執行查詢並將結果返回給Excel。查詢需要輸入一個年份字符串作爲輸入參數。我用Python調用它,如下所示:Pandas.read_sql失敗,DBAPIError 07002:COUNT字段不正確或語法錯誤

def flatten(l): 
    for el in l: 
     try: 
      yield from flatten(el) 
     except TypeError: 
      yield el 

my_list = (previous_year_1,previous_year,current_year) 
sql = 'select year,sum(sales)/case when sum(t_count)=0 then 1 else sum(t_count) as tx_sales from t_sales where year in ({1})'+ 'group by year' + 'order by year' 
sql = sql.format ('?',','.join('?' * len(my_list))) 
params = tuple(flatten(member_list)) 
ind_data = pd.read_sql(sql,engine,params) 

查詢本身在修復end子句之後,在通過SSMS運行時完美工作。只是不通過Python代碼。我得到的錯誤是:

Traceback (most recent call last): 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1139, in _execute_context 
    context) 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 450, in do_execute 
    cursor.execute(statement, parameters) 
pyodbc.Error: ('07002', '[07002] [Microsoft][SQL Server Native Client 11.0]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') 

The above exception was the direct cause of the following exception: 

Traceback (most recent call last): 
    File "<string>", line 1, in <module> 
    File "c:\pbp_proj\pbp_proj.py", line 61, in pull_metrics 
    ind_data = pd.read_sql_query(sql, engine, params) 
    File "C:\Anaconda3\lib\site-packages\pandas\io\sql.py", line 411, in read_sql_query 
    parse_dates=parse_dates, chunksize=chunksize) 
    File "C:\Anaconda3\lib\site-packages\pandas\io\sql.py", line 1128, in read_query 
    result = self.execute(*args) 
    File "C:\Anaconda3\lib\site-packages\pandas\io\sql.py", line 1022, in execute 
    return self.engine.execute(*args, **kwargs) 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1989, in execute 
    return connection.execute(statement, *multiparams, **params) 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 906, in execute 
    return self._execute_text(object, multiparams, params) 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1054, in _execute_text 
    statement, parameters 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1146, in _execute_context 
    context) 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1341, in _handle_dbapi_exception 
    exc_info 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 188, in raise_from_cause 
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value) 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 181, in reraise 
    raise value.with_traceback(tb) 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1139, in _execute_context 
    context) 
    File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 450, in do_execute 
    cursor.execute(statement, parameters) 
sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('07002', '[07002] [Microsoft][SQL Server Native Client 11.0]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') 

我怎樣才能解決這個問題?

+0

你用'params = tuple(flatten(member_list))'來試試我的解決方案嗎?我猜這個錯誤是由於'len(tuple(flatten(member_list)))!= len(my_list)' – MaxU

回答

2

您錯過了您的sql字符串中的一個空格,位於yearorder by之間。

試試這個:

sql = 'select year,sum(sales)/case when sum(t_count)=0 then 1 else sum(t_count) as tx_sales from t_sales where year in ({1}) '+ 'group by year ' + 'order by year ' 
+2

在組年之前還錯過了一個空間 –

+0

感謝您的響應NolanShang和@MYGz試圖添加空格,但沒有運氣。仍然會得到相同的錯誤。 – Bee

+0

print final'sql'和'params'並顯示你的'flatten()'函數。包括你的問題。 – MYGz

3

正如@MYGz已經提到有order by之前丟失的空間。

除此之外,在group by之前還有一個缺失空間,最重要的一個 - 您的CASE ...聲明應該用END「關閉」。

也就是說試試下面的SQL:

sql = 'select year,sum(sales)/(case when sum(t_count)=0 then 1 else sum(t_count) end)' \ 
     +' as tx_sales from t_sales where year in ({1})'+' group by year order by year' 

您可以使用直接使用.format()您的SQL模式 - 沒有必要將其覆蓋:

params = tuple(flatten(member_list)) 
ind_data = pd.read_sql(sql.format('?',','.join('?' * len(params))), engine, params) 
0

解決了這個。有點破解,但有效。我首先將其改爲使用pyodbc而不是sqlalchemy。 所以我的查詢字符串變成了:

  sql = 'select year,sum(sales)/case when sum(t_count)=0 then 1 else sum(t_count) end as tx_sales from t_sales where year in (?,?,?) '+ ' group by year' + ' order by year' 

      ind_data = pd.read_sql(sql, conn, params=member_list) 
      summary = ind_data.transpose() 

我只好再添加其他AND子句與另一個參數。爲此我創建了:

cur_params = (member_list) 
    cur_params.append(var_premium) 

然後將cur_params傳遞給ind_data。

ind_data = pd.read_sql(sql, conn, params=cur_params) 

這兩組數據現在都能正確返回數據。

謝謝大家閱讀我的文章和所有建議。

相關問題