[问题] pyodbc用DataFrame当其中一个Table

楼主: duncanfun (D.F)   2021-03-24 20:35:10
要怎么让Dataframe当其中一个Table,执行SQL查询
使用情境大概是这样
有一个装我整理好的客户资料的Excel,大概有几百个人,内容大概是
客户名称 ID 联络人 联络人电话
Red 12 Amy #1234
.......
我想要在连线到数据库,但是不更改或插入数据库,把这些人的资料捞出来
我要怎么让这个Excel成为From的一个Table
import pyodbc
import pandas as pd
cnxn=pyodbc.connect('连线参数')
cursor=cnxn.cursor()
customer_xlsx=pd.read_excel(r'客户资料_已整理.xlsx')
"""以下为SQL语法,像这样把customer_xlsx当成一个Table"""
report="""
SELECT customer_xlsx.ID, CUSTOMER.ITEM, CUSTOMER.DATE
FROM CUSTOMER, customer_xlsx
WHERE customer_xlsx.ID=CUSTOMER.ID
AND customer_xlsx.联络人='Amy'
AND CUSTOMER.DATE>#2021/1/1#
"""
实际上当然会比这个再多更多条件,也会再交叉到其他数据库内的Table
我想的解决方法是要让pandas先把资料整理好
rule=customer_xlsx["联络人"]=="Amy"
filter=customer_xlsx[rule]
ID_excel="'"
i=0
while i<len(filter):
ID_excel=ID_excel+filter.iloc[i,1]+"','"
i+=1
ID_excel=ID_excel[:len(ID_excel)-2]
之后再把ID_excel丢到SQL里面用In去找
但是这样做感觉很繁琐,而且单位会python语法也只有我,要推广出去会有难度
之后如果发生更复杂的语法可能会遇到瓶颈
所以有办法让Dataframe成为pyodbc的一个Table,而且是在不动到数据库的条件下捞出资
料吗
作者: cuteSquirrel (松鼠)   2021-03-24 22:14:00
pandasql 套件比较接近你想做的事情用SQL语法去捞dataframe的资料https://pypi.org/project/pandasql/
作者: celestialgod (天)   2021-03-25 16:38:00
https://reurl.cc/e9n3pM How about temp table?create a temp table in db and join it withyour table阿没看到不插入资料下....
作者: cuteSquirrel (松鼠)   2021-03-25 19:37:00
对阿,用接口去捞,不会动到原本公司内网的DB
作者: MAGICXX (逢甲阿法)   2021-03-26 22:47:00
捞出来的table存变量 然后再对这个变量做查询?不然存本机csv再read_csv做查询之类的?反正再复杂也没关系 你就做个接口 给他们用就好 里面再怎么复杂 他们也不知道(?

Links booklink

Contact Us: admin [ a t ] ucptt.com