我正在尝试使用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
没有引发异常。如何测试产生的游标或连接以知道发生了问题,以及如何获得错误消息?
非常感谢。
EDIT以下是完整的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
EDIT 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')
我能够使用以下代码重新创建您的问题,该代码以静默方式失败:
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()
然而,我可以通过在sql
字符串的开头添加SET NOCOUNT ON;
来获得引发适当的IntegrityError
异常的代码:
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:UsersGordDesktoppyOdbc.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)')