2016-11-15 65 views
0

我有一个复杂的SQL Server查询,我需要从python执行。从Python复杂的SQL Server查询

SQL查询看起来像:

SELECT * 
FROM(
    SELECT DATEADD(HOUR, CONVERT(INT, SUBSTRING(hour_id, 2, 2)), CAST(FECHA as DATETIME)) as 'Time_', value 
    FROM 
     (
     SELECT * FROM [MyTable] 
     ) as sel 
    UNPIVOT(value for hour_id in (H01, H02, H03, H04, H05, H06, H07, H08, H09, H10, H11, H12, H13, H14, H15, H16, H17, H18, H19, H20, H21, H22, H23, H24)) as unpvte 
) as Q1; 

我创建运行查询和转结局大熊猫功能:

import pandas as pd 
import numpy as np 
import datetime 
import pypyodbc 

def execute_sql_command(database_name, server_name, user, password, SQLCommand, index_col=0): 
     """ 
     Executed a query in an SQL Server database and returns a Pandas DataFrame 
     :param database_name: Name of the Database 
     :param SQLCommand: SQL command with no comments 
     :param index_col: Index of the column 
     :return: Pandas DataFrame 
     """ 

     connection_string = 'DRIVER={SQL Server};Database=' + database_name \ 
          + ';SERVER=' + server_name \ 
          + ';UID=' + user \ 
          + ';PWD=' + password 

     connection = pypyodbc.connect(connection_string) 
     cursor = connection.cursor() 

     data = list() 
     idx = list() 
     cursor.execute(SQLCommand) 
     hdr = [tuple[0] for tuple in cursor.description] 

     hdr.pop(index_col) 

     results = cursor.fetchone() 
     if results is not None: 
      results = list(results) 

     while results: 
      idx.append(results[index_col]) # add the index 
      results.pop(index_col) # remove the index from the row (we already accounted for it) 
      data.append(results) # 
      results = cursor.fetchone() 
      if results is not None: 
       results = list(results) 

     connection.close() 

     data = np.array(data) 
     df = pd.DataFrame(data=data, columns=hdr, index=idx) 

     return df 

我收到此错误:

pypyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax close to 'L'.")

我的代码适用于简单的查询,如SELECT * FROM Table,但无法处理这个复杂的查询。该查询在Microsoft SQL Server Management Studio中可用。

回答

1

嗯,我想出了问题所在。

我正在阅读来自.sql文件的查询。所以文件必须是UTF-8格式。

然后在一行中组成SQL命令,这是删除\n字符。