passing a date to a function in python that is calling sql server [duplicate]

廉价感情. 提交于 2020-02-04 04:15:51

问题


I am trying to pass date1 and date 2 to a function in python that creates a dataframe from a sql server

  import datetime as dt
  import pandas as pd
  import pyodbc
  import sqlalchemy
  from pandas import Series,DataFrame
  cnx=sqlalchemy.create_engine("mssql+pyodbc://Omnius:MainBrain1@172.31.163.135:1433/Basis?driver=/opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0")

def func1(date1,date2):
sqlquery = "select top 10000 * from Pretty_Txns where Pay_Date between '"+date1+"' and '"+date2+"'"
df=pd.read_sql(sqlquery,cnx)

When I try and call this function from ipython

  func1(dt.date(2015,05,01),dt.date(2015,05,02))

  ----> 8     sqlquery = "select top 10000 * from Pretty_Txns where Pay_Date between  '"+date1+"' and '"+date2+"'"

 TypeError: cannot concatenate 'str' and 'datetime.date' objects

How should I call the function so that I dont get the type error.


回答1:


This should get you started. Your SQL will likely not work unless the date formats match. Print out the sqlquery and test in CLI.

Example conversion:

t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')


def func1(date1,date2):
      strDate1 =  date1.strftime('%m/%d/%Y')
      strDate2 =  date2.strftime('%m/%d/%Y')

      sql = "select top 10000 * from Pretty_Txns where Pay_Date > '%s' and Pay_Date < '%s'  " %    (strDate1, strDate2)
      return sql

sqlquery = func1( DateOne,DateTwo )
#print sqlquery. 

df=pd.read_sql(sqlquery,cnx)



回答2:


sqlquery = "select top 10000 * from Pretty_Txns where Pay_Date between :date1 and :date2"

df=pd.read_sql(sqlquery,cnx, params=dict(date1=date1, date2=date2))

If your driver does not support named placeholders then use question marks as before and pass in a list of [date1, date2] as the value to params.



来源:https://stackoverflow.com/questions/37798229/passing-a-date-to-a-function-in-python-that-is-calling-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!