I’m trying to do a very simple INSERT using VB.NET. For some reason I’m getting a SqlException on every insert though. The data is inserted, but still get the following:
Violation of PRIMARY KEY constraint ‘PK_User’. Cannot insert duplicate key in object ‘dbo.Employee’. The statement has been terminated
When I check in SQL Management Studio, the data is succesfully inserted.
Here is the code where the problem is happening
Try conn.Open() Dim insertSQL As String = 'insert into Employee(uName, firstName, lastName, On_Switch, On_Phone) ' + 'values('' & uName & '', '' & firstName & '', '' _ & lastName & '', '' & onSwitch & '', '' & onPhone & '')' Dim AddCom As SqlCommand = New SqlCommand(insertSQL, conn) If (AddCom.ExecuteNonQuery() = 1) Then lblError.Text = 'User Added.' ' string urlBack = '../ViewAsset.aspx?DeptID=' + DeptID; ' Response.Redirect(urlBack); End If conn.Close() Catch ex As SqlException Dim ExMsg As String = ex.Message.ToString() lblError.Text = ExMsg
I went back and tested the same code in C# and there is no Exception thrown. It seems to be something small I’m doing in VB, but I’m lost as to what it is.
Two theories. Either your code is being executed twice, or there’s a trigger on the Employee table that’s attempting an insert following the successful insert. (Edit: @Mitchel Sellers is exactly right, if the same code works in c# it’s absolutely not a trigger issue.)
My hunch is that your code is being executed twice. Try running with the debugger attached and a breakpoint set on the ExecuteNonQuery – I think you’ll find that some other method calls this method multiple times.
@Mitchel Sellers – GOOD CATCH ON THE SQL INJECTION BUG! Parameters, please!