我正在執行SQL命令以在數據庫表中創建新記錄並獲取創建的記錄的ID。但是,由VB代碼未拾取的SQL命令(未初始化的非空字段)會生成約束錯誤。該代碼大致爲: -SqlCommand.ExecuteReader無法報告錯誤
connection = New SqlConnection(connection_string)
connection.Open()
sql_command = New SqlCommand(command) 'command = the SQL command to execute
sql_command.Connection = connection
sql_command.Parameters.AddRange(sql_parameters.ToArray()) ' sql_parameters is a parameter to the function
reader = sql_command.ExecuteReader()
If reader IsNot Nothing Then
If reader.HasRows Then
While reader.Read
response_handler(reader, data) 'response handler is a callback which populates the data object
End While
End If
reader.Close()
End If
reader對象爲非null,但不包含數據,並且不會生成異常。 SQL命令是: -
insert into [table] ([column1], [column2], [column3], [column4])
output Inserted.[pk]
values (@1, @2, @3, @4)
執行使用SQL Server Management Studio中的SQL語句,我得到的錯誤: -
Msg 515, Level 16, State 2, Line 2
Cannot insert the value NULL into column 'somecolumn', table 'tablename'; column does not allow nulls. INSERT fails.
我還增加了一個處理程序InfoMessage
事件SqlConnection
對象但即使當我將FireInfoMessageEventOnUserErrors
設置爲true時也不會被調用。
爲什麼我沒有收到錯誤,以及確保將錯誤報告給VB的正確方法是什麼?
我正在使用Visual Studio 2008.
我不希望拋出異常直到調用'reader.Read()'方法,並且它永遠不會被調用,因爲'HasRows'爲false。我正在嘗試(不成功)找到的是'HasRows'設置的點,以便提供正確的答案。您可以跳過驗證'如果reader.HasRows Then..',因爲如果它沒有行,您將永遠不會進入'While reader.Read'循環(如果沒有行,它將在第一次運行時爲假) 。 – GarethD
@GarethD:嗯,我會嘗試刪除HasRows檢查,看看它是否開始產生錯誤。我會在嘗試後更新問題(週末後) – Skizz
旁註:刪除第一個到If語句。他們什麼都不做。 – usr