user2139876
user2139876

Reputation: 29

SqlCommand.ExecuteNonQuery() not throwing expected error in VB.net

Me.mycom.CommandText = "INSERT INTO Schritte_WegGruppen VALUES (" & SchrittID.ToString & ", " & WegGruppeID.ToString & ", '...')"
Me.mycom.ExecuteNonQuery()

The above two lines execute perfectly fine in VB .NET, but they throw this exception in C#:

The statement has ended. Violation of the PRIMARY KEY restriction "PK_Schritte_WegGruppen_ID_Schritte_ID_WegGruppen". A duplicate key can not be inserted into the object "dbo.steps_pathgroups". The double key value is (1, 1).

This exception is totally logical and I get the same exception when I execute this query in SQL Server Management Studio too. I expect an error in the VB code when I run it but I don't get any exception. I do not understand why.

Is there a difference between how ExecuteNonQuery() works in VB.Net and C#?

Here is the complete VB code which I'm trying to translate to C#.

 Try
        '*** In die Modul Datenbank wechseln ***
        Me.mycom.CommandText = "USE " & ModulDB
        Me.mycom.ExecuteNonQuery()

        Me.mycom.CommandText = "INSERT INTO Schritte_WegGruppen VALUES (" & SchrittID.ToString & ", " & WegGruppeID & ", '...')"
        Me.mycom.ExecuteNonQuery()

        Return 1
    Catch ex As Exception
        Me.ErrMess = ex.Message
        Return -1

And the translated C# code is here:

try 
{
    //*** In die Modul Datenbank wechseln ***
    this.mycom.CommandText = "USE " + ModulDB;
    this.mycom.ExecuteNonQuery();

    this.mycom.CommandText = "INSERT INTO Schritte_WegGruppen VALUES (" + SchrittID.ToString() + ", " + WegGruppeID.ToString() + ", '...')";
    this.mycom.ExecuteNonQuery();

    return 1;
}
catch (Exception ex)
{
    this.ErrMess = ex.Message;
    return -1;
}

I hope my question is clearer now.

Upvotes: 0

Views: 1865

Answers (2)

Manuel Mar
Manuel Mar

Reputation: 1

Catch ex As Exception

Please replace Catch ex As Exception with Catch ex As SqlException, I had the same problem and now I can catch the exception.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063298

ADO.NET - or more generally any library code - almost always doesn't know or care what language the calling code is using. As such, there are three likely reasons for what you describe:

  • the data / system-state is different in your two test cases meaning that it genuinely isn't erroring in one case, but is in the other - because they are talking about different scenarios
  • it is erroring, but you have some surrounding exception-handling code (typically: try/catch or On Error) that is swallowing the exception
  • you have made an error translating the code between the two languages, and the actual string you are executing is different

Upvotes: 1

Related Questions