[英]Python create dataframe from sql query result
I have sql query with multiple temporary table creation and one final select statement.我有多个临时表创建和一个最终选择语句的 sql 查询。
Let's imagine query example:让我们想象一下查询示例:
select
t1.Variable11,
t1.Variable12,
t2.Variable13
into #R1
from t1
join t2
on t1.Key1= t2.key1 and t1.Key2= t2.key2
where t1.Variable1 > 100
select
t3.Variable21,
t3.Variable22,
t4.Variable23
into #R2
from t3
join t4
on t3.Key1= t4.key1 and t3.Key2= t4.key2
where t3.Variable1 > 200
select
#R1.*,
#R2.*
from #R1
join #R2
on #R1.Variable11= #R2.Variable21
I connect to sql server with pyodbc connector:我使用 pyodbc 连接器连接到 sql server:
connection = pyodbc.connect(driver='{SQL Server Native Client 11.0}', server=server_name,
database=db_name, trusted_connection='yes', MARS_Connection='yes')
I do not want to re-write code.我不想重新编写代码。 I just want to write function which will return pandas dataframe.我只想编写将返回熊猫数据帧的函数。 When i try to use pandas.read_sql()
function i receive error:当我尝试使用pandas.read_sql()
函数时,我收到错误:
TypeError: 'NoneType' object is not iterable TypeError: 'NoneType' 对象不可迭代
When i try to use pyodbs.execute()
i receive error:当我尝试使用pyodbs.execute()
我收到错误:
No results.没有结果。 Previous SQL was not a query.以前的 SQL 不是查询。
how to handle a sql script with multiple temporary tables creation and one final select statements?如何处理具有多个临时表创建和一个最终选择语句的 sql 脚本?
import pandas as pd
from sqlalchemy import *
engine = create_engine('mssql+pyodbc://python:python@Database/Tablename?driver=SQL+Server+Native+Client+11.0')
connection = engine.connect()
SQL='select * from ' + Tablename
Tfrom_sql=pd.read_sql(SQL, connection)
connection.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.