pymssql ( python module ) unable to use temporary tables

六眼飞鱼酱① 提交于 2019-12-04 21:03:35

Update: July 2016

The previously-accepted answer is no longer valid. The second "will NOT work" example does indeed work with pymssql 2.1.1 under Python 2.7.11 (once conn.autocommit(1) is replaced with conn.autocommit(True) to avoid "TypeError: Cannot convert int to bool").

For those who run across this question and might have similar problems, I thought I'd pass on what I'd learned since the original post. It turns out that you CAN use temporary tables in pymssql, but you have to be very careful in how you handle commits.

I'll first explain by example. The following code WILL work:

testQuery = """
CREATE TABLE #TEST (
[name] varchar(256)
,[age] int )

INSERT INTO #TEST
values ('Mike', 12)
,('someone else', 904)

"""

conn = pymssql.connect(host=sqlServer, user=sqlID, password=sqlPwd, \
    database=sqlDB) ## obviously setting up proper variables here...
conn.autocommit(1)
cur = conn.cursor()
cur.execute(testQuery)
cur.execute("SELECT * FROM #TEST")
tmp = cur.fetchone()
tmp

This will then return the first item (a subsequent fetch will return the other):

('Mike', 12)

But the following will NOT work

testQuery = """
CREATE TABLE #TEST (
[name] varchar(256)
,[age] int )

INSERT INTO #TEST
values ('Mike', 12)
,('someone else', 904)

SELECT * FROM #TEST

"""

conn = pymssql.connect(host=sqlServer, user=sqlID, password=sqlPwd, \
    database=sqlDB) ## obviously setting up proper variables here...
conn.autocommit(1)
cur = conn.cursor()
cur.execute(testQuery)
tmp = cur.fetchone()
tmp

This will fail saying "pymssql.OperationalError: No data available." The reason, as best I can tell, is that whether you have autocommit on or not, and whether you specifically make a commit yourself or not, all tables must explicitly be created AND COMMITTED before trying to read from them.

In the first case, you'll notice that there are two "cur.execute(...)" calls. The first one creates the temporary table. Upon finishing the "cur.execute()", since autocommit is turned on, the SQL script is committed, the temporary table is made. Then another cur.execute() is called to read from that table. In the second case, I attempt to create & read from the table "simultaneously" (at least in the mind of pymssql... it works fine in MS SQL Server Management Studio). Since the table has not previously been made & committed, I cannot query into it.

Wow... that was a hassle to discover, and it will be a hassle to adjust my code (developed on MS SQL Server Management Studio at first) so that it will work within a script. Oh well...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!