I am using Python to extract data from SQL by using ODBC to linking Python to SQL database.
(我正在使用Python通过使用ODBC将Python链接到SQL数据库来从SQL提取数据。)
when I do the query, I need to use variables in the query to make my query result changeable. (在执行查询时,我需要在查询中使用变量以使查询结果可更改。)
For example, my code is: (例如,我的代码是:)
import pyodbc
myConnect = pyodbc.connect('DSN=B1P HANA;UID=***;PWD=***')
myCursor = myConnect.cursor()
Start = 20180501
End = 20180501
myOffice = pd.Series([1,2,3])
myRow = myCursor.execute("""
SELECT "CALDAY" AS "Date",
"/BIC/ZSALE_OFF" AS "Office"
FROM "SAPB1P"."/BIC/AZ_RT_A212"
WHERE "CALDAY" BETWEEN 20180501 AND 20180501
GROUP BY "CALDAY","/BIC/ZSALE_OFF"
""")
Result = myRow.fetchall()
d = pd.DataFrame(columns=['Date','Office'])
for i in Result:
d= d.append({'Date': i.Date,
'Office': i.Office},
ignore_index=True)
You can see that I retrieve data from SQL database and save it into a list (Result), then I convert this list to a data frame (d).
(您可以看到我从SQL数据库检索数据并将其保存到列表(结果)中,然后将该列表转换为数据框(d)。)
But, my problems are:
(但是,我的问题是:)
- I need to specify a start date and an end data in myCursor.execute part, something like
"CALDAY" BETWEEN Start AND End
(我需要在myCursor.execute部分中指定开始日期和结束数据,例如"CALDAY" BETWEEN Start AND End
)
- Let's say I have 100 offices in my data.
(假设我的数据中有100个办公室。)
Now I just need 3 of them (myOffice). (现在我只需要3个(myOffice)。)
So, I need to put a condition in myCursor.execute part, like myOffice in (1,2,3)
(因此,我需要在myCursor.execute部分中放置一个条件,例如myOffice in (1,2,3)
)
In R, I know how to deal with these two problems.
(在R中,我知道如何处理这两个问题。)
the code is like: (该代码是这样的:)
office_clause = ""
if (myOffice != 0) {
office_clause = paste(
'AND "/BIC/ZSALE_OFF" IN (',paste(myOffice, collapse=", "),')'
)
}
a <- sqlQuery(ch,paste(' SELECT ***
FROM ***
WHERE "CALDAY" BETWEEN',Start,'AND',End,'
',office_clause1,'
GROUP BY ***
'))
But I do not know how to do this in Python.
(但是我不知道如何在Python中做到这一点。)
How can I do this? (我怎样才能做到这一点?)
ask by Feng Chen translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…