python - pyodbc 不会抛出 SQL Server 错误

标签 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

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:\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)')

关于python - pyodbc 不会抛出 SQL Server 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20504338/

相关文章:

python - mysql 子查询和 python 集

python - 如何检测瓷砖上的裂缝?

python - 动态导入模块

sql-server - 是否可以以编程方式区分 SQL Server 的版本?

sql-server - 您可以搜索 SQL Server 2005 存储过程内容吗?

sql-server - SSMS无法识别联接语法

python - 在 Pandas 和 pyodbc SQL Server 中使用百分比 (%) 没有错误

python - 将装饰器的函数传递给 Python RQ

python - 为什么使用 pyodbc 访问大于 511 的字符字段时 count() 返回 0?

python - 如何处理 CSV 文件中 DECIMAL 列的缺失值