【问题标题】:Executing sequence of MS sql queries with temp tables in python在 python 中使用临时表执行 MS sql 查询序列
【发布时间】:2017-12-06 21:47:38
【问题描述】:

目前正在尝试使用pyodbc 和pandas 读取sql 查询序列(来自MS sql server)并作为数据框进行检查,在序列中的第一个查询中出现以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-95-5eec1638614b> in <module>()
    285 for count, q in enumerate(sql_in):
    286     print count
--> 287     frame_in = pd.read_sql(q, cnxn)
    288 print frame_in.head(n=10)
    289 

/home/mapr/anaconda2/lib/python2.7/site-packages/pandas/io/sql.pyc in read_sql(sql, con, index_col, coerce_float, params, parse_dates, columns, chunksize)
    497             sql, index_col=index_col, params=params,
    498             coerce_float=coerce_float, parse_dates=parse_dates,
--> 499             chunksize=chunksize)
    500 
    501     try:

/home/mapr/anaconda2/lib/python2.7/site-packages/pandas/io/sql.pyc in read_query(self, sql, index_col, coerce_float, params, parse_dates, chunksize)
   1598         args = _convert_params(sql, params)
   1599         cursor = self.execute(*args)
-> 1600         columns = [col_desc[0] for col_desc in cursor.description]
   1601 
   1602         if chunksize is not None:

TypeError: 'NoneType' object is not iterable

相关代码sn-p如下:

sql_in = """
SET NOCOUNT ON;
select <stuff> from <table1> into #<temptable1>
----SPLIT
SET NOCOUNT ON;
select <stuff> from <table2> into #<temptable2>
----SPLIT
SET NOCOUNT ON;
select <stuff> from <table3> into #<temptable3>
----SPLIT
SET NOCOUNT ON;
select <stuff> from <table4> <joined with temptables1-3> into #<temptable4>
""".split('----SPLIT')

for count, q in enumerate(sql_in):
    print count
    frame_in = pd.read_sql(q, cnxn)

这样做是因为只对最终的临时表感兴趣(使用split,因为发布了here 的建议)。

可以通过运行确认pyodbc配置正确:

cnxn = pyodbc.connect(cnxn_str)
cursor = cnxn.cursor()

#Sample select query
print 'Testing db connection...'
cursor.execute("SELECT @@version;") 
row = cursor.fetchone() 
while row: 
    print row[0] 
    row = cursor.fetchone()

并实际获取服务器版本。

任何想法为什么会发生这种情况以及如何解决?谢谢。

【问题讨论】:

  • 我相信 DB-API 指定 .execute() 每个命令只允许一个查询。
  • @bernie - 我刚刚又看了一遍PEP249,我没有看到任何提及。当然,如果 ODBC 驱动程序允许,匿名代码块(多语句批处理)可以工作(并且 Microsoft 的 SQL Server ODBC 驱动程序确实允许)。
  • 啊,好的。谢谢@GordThompson。那我一定是搞错了。

标签: python sql-server pandas pyodbc


【解决方案1】:

我相信这是因为前几个查询没有返回任何数据。 Pandas read_sql 期望数据返回。您应该只使用 pyodbc 执行函数来运行这些查询。

【讨论】:

  • ... 或者尝试将整个匿名代码块(不拆分)传递给read_sql? (现在不能尝试;我的手机上没有熊猫……)
  • 那会更好,我只是想回答为什么他们的代码不起作用的问题
  • 这篇文章回答了为什么代码不起作用的原始问题,尽管最终实现了用户 GordThompson 建议的解决方案。谢谢你们。
  • 不也是SELECT &lt;stuff&gt; INTO #&lt;temptable1&gt; FROM &lt;table1&gt;吗?我相信您的 INTO / FROM 的顺序在您的原始 SQL 中是相反的。
  • @FlipperPA 我使用的是 MS SQL Server,所以它的发布方式适合我。
猜你喜欢
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
  • 2013-09-24
相关资源
最近更新 更多