我在错误处理方面遇到问题。通过 VB 程序,我想向 SQL Server 2008 R2 表添加重复键。我正在使用以下代码:
Public Shared Function AddCatPlanilla(ByVal CatPlanilla As CatPlanilla) As Boolean
Dim connection As SqlConnection = EnterpriseDB.GetConnection
Dim insertStatement As String _ = "INSERT [dbo].[CatPlanilla] " _
& "([CodEmpr], [TipoCatalogo], [CodAsoc], [Descripcion], [DescripcionCorta]) " _
& "VALUES (@CodEmpr, @TipoCatalogo, @CodAsoc, @Descripcion, @DescripcionCorta)"
Dim insertCommand As New SqlCommand(insertStatement, connection)
insertCommand.CommandType = CommandType.Text
insertCommand.Parameters.AddWithValue("@CodEmpr", CatPlanilla.m_CodEmpr)
insertCommand.Parameters.AddWithValue("@TipoCatalogo", CatPlanilla.m_TipoCatalogo)
insertCommand.Parameters.AddWithValue("@CodAsoc", CatPlanilla.m_CodAsoc)
insertCommand.Parameters.AddWithValue("@Descripcion", CatPlanilla.m_Descripcion)
insertCommand.Parameters.AddWithValue("@DescripcionCorta", CatPlanilla.m_DescripcionCorta)
Try
connection.Open()
Dim count As Integer = insertCommand.ExecuteNonQuery()
If count > 0 Then
Return True
Else
Return False
End If
Catch ex As SqlException
Throw ex
Finally
connection.Close()
End Try
End Function
当我想添加重复键时,sqlexception 不会捕获错误,屏幕上会显示以下信息(停止程序):
System.Data.SqlClient.SqlException occurred
Class=14
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=1
Message=Cannot insert duplicate key row in object 'dbo.CatPlanilla' with unique index
'IX_CatPlanilla'. The duplicate key value is (001, LT, Lima).
The statement has been terminated.
我不知道是什么原因造成的,也不知道是 SQL 服务器配置问题还是 Visual Studio 配置问题。
我想强调的是,程序永远不会跳转到 CATCH 部分。程序停在“Dim count As Integer = insertCommand.ExecuteNonQuery ()”那一行,可惜我不能发送图片,抱歉