如何在Python脚本中执行多个SQL语句?

时间:2017-08-10 22:26:41

标签: python sql sql-server pandas

我正在使用Python中的以下代码模板(使用Atom进行构建/编写)。

import pyodbc
import pandas as pd
import win32com.client


cnxn = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL 
Server}',server ='prodserver', database = 'XXXX')

cnxn.setdecoding(pyodbc.SQL_WCHAR, encoding='utf-8')
cnxn.setencoding(str, encoding='utf-8')
cnxn.setencoding(unicode, encoding='utf-8', ctype=pyodbc.SQL_CHAR)
cursor = cnxn.cursor()
script ="""SELECT AccountsCount.AccountClass, COUNT(*) as Count
   FROM
        (SELECT *
        FROM XXXX.dbo.table
        where SubNo='001'
        AND (DATENAME(WEEKDAY, GETDATE()) = 'Sunday' AND
   convert(date,AddDate) = DATEADD(DAY, -2, CAST(GETDATE() as DATE))
  ) OR
  (DATENAME(WEEKDAY, GETDATE()) = 'Monday' AND
   convert(date,AddDate) = DATEADD(DAY, -3, CAST(GETDATE() as DATE))
  ) OR
  (DATENAME(WEEKDAY, GETDATE()) = 'Sunday' AND
   convert(date,AddDate) = DATEADD(DAY, -2, CAST(GETDATE() as DATE))
  ) OR
  (DATENAME(WEEKDAY, GETDATE()) NOT IN ('Sunday', 'Monday') AND
   convert(date,AddDate) = DATEADD(DAY, -1, CAST(GETDATE() as DATE))
  )) AS AccountsCount
  Group by AccountsCount.AccountClass
  """

df = pd.read_sql_query(script,cnxn)
writer = pd.ExcelWriter ('ExcelFile.xlsx')
df.to_excel(writer, sheet_name = 'Data Export')
writer.save()

xlApp = win32com.client.DispatchEx('Excel.Application')
xlsPath = ('OtherExcelFile.xlsm')
wb = xlApp.Workbooks.Open(Filename=xlsPath)
xlApp.Run('CopyIntoOutlook')
wb.Save()
xlApp.Quit()

我需要做的就是在这个脚本中添加第二个完全独立的SQL命令,该命令运行完美无瑕,并按照上面的要求执行我需要的操作。我的附加脚本是这样的

script= """ select AccountClass, COUNT(*) as Count
    FROM XXXX.dbo.table
    where SubNo='001'
    AND AddDate >= '1/1/2017'
  Group by AccountClass """

对于我在尝试添加到脚本中所做的任何事情,我都没有运气,任何帮助都非常有用!您会注意到第二个脚本使用的是与原始脚本相同的数据库和表格,我只需要YTD数据以及前一天查看的顶级查询。

0 个答案:

没有答案