pyodbc不会抛出SQL Server错误

时间:2013-12-10 20:16:47

标签: python sql-server pyodbc

我正在尝试使用pyodbc(使用Python 2.7)来调用存储过程以将记录插入到SQL Server 2012表中。我正在通过一张临时桌子。

我抛弃了我的sql,当通过SQL Server管理控制台执行时,它生成了以下外键错误:

Msg 547, Level 16, State 0, Procedure spInsertBondTickerValues, Line 26
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__BondTickerValue__756D6ECB".
The conflict occurred in database "QuantDev", table "dbo.Tickers".
The statement has been terminated.

但是,pyodbc没有引发异常。如何测试生成的游标或连接以了解发生了问题,以及如何获取错误消息?

非常感谢。

编辑以下是完整的SQL文本:

DECLARE @rawTbl [dbo].TickerValueTableType
INSERT INTO @rawTbl (Ticker, BBName, LastValue, ValueTime, SourceDescr) VALUES
('IBM', 'Equity', 179.230000, '2013-11-01 00:00:00.000000', 'Bloomberg'),
('SPX', 'Index', 1803.710000, '2013-12-10 00:00:00.000000', 'Bloomberg')
EXEC [dbo].spInsertBondTickerValues @rawTbl

编辑2 以下是相关的Python代码:

def execSQLwithCommit(self, sql):
    cursor = self.conn.cursor()
    cursor.execute(sql)
    self.conn.commit()

之前已通过

进行连接
self.conn = pyodbc.connect(app      = appName,
                           driver   = '{SQL Server Native client 11.0}',
                           server   = server,
                           database = db,
                           Trusted_Connection = 'yes')

1 个答案:

答案 0 :(得分:6)

我能够使用以下代码重新创建您的问题,该代码无声地失败:

import pyodbc
cnxn = pyodbc.connect('DSN=myDb;')
cursor = cnxn.cursor()
sql = """   
DECLARE @rawTbl dbo.ClientAddressInputType;
INSERT INTO @rawTbl (ClientID, Addr1) VALUES 
(2, 'higgy'), 
(3, 'jiggy'); 
EXEC dbo.AddClientAddress @rawTbl
"""
cursor.execute(sql)
cursor.commit()
cnxn.close()

但是,我可以通过在IntegrityError字符串的开头添加SET NOCOUNT ON;来获取相应的sql例外代码:

import pyodbc
cnxn = pyodbc.connect('DSN=myDb;')
cursor = cnxn.cursor()
sql = """   
SET NOCOUNT ON;
DECLARE @rawTbl dbo.ClientAddressInputType;
INSERT INTO @rawTbl (ClientID, Addr1) VALUES 
(2, 'higgy'), 
(3, 'jiggy'); 
EXEC dbo.AddClientAddress @rawTbl
"""
cursor.execute(sql)
cursor.commit()
cnxn.close()

导致

Traceback (most recent call last):
  File "C:\Users\Gord\Desktop\pyOdbc.py", line 12, in <module>
    cursor.execute(sql)
IntegrityError: ('23000', '[23000] [Microsoft][SQL Server Native Client 10.0][SQL Server]The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ClientAddresses_Clients". The conflict occurred in database "myDb", table "dbo.Clients", column \'ClientID\'. (547) (SQLExecDirectW); [01000] [Microsoft][SQL Server Native Client 10.0][SQL Server]The statement has been terminated. (3621)')