【发布时间】: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