Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server return long.parse show error

My current problem is with SQL server. I'm writing my own queries and one query is for INSERT data inside table. That's easy to do. What isn't easy is error i received during testing. I just breakpointed every steps and all works fine, except final result.

Is the problem with long? Because when I use bool, it works perfectly, but I need to use long.

Now let's see what I have inside code:

public long Create(TPerson person)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var insert = string.Format(@"INSERT INTO CisOsoba(Jmeno, Prijmeni, Email, TelKlapka, TelKlapka2, TelMob)
                                         VALUES(@jmeno, @prijmeni, @email, @telKlapka, @telKlapka2, @telMob)");

        connection.Open();
        SqlCommand cmd = new SqlCommand(insert, connection);

        cmd.Parameters.AddWithValue("@jmeno", person.FirstName);
        cmd.Parameters.AddWithValue("@prijmeni", person.LastName);
        cmd.Parameters.AddWithValue("@email", person.Email);
        cmd.Parameters.AddWithValue("@telKlapka", person.Phone1);
        cmd.Parameters.AddWithValue("@telKlapka2", person.Phone2);
        cmd.Parameters.AddWithValue("@telMob", person.PhoneMob);

        return long.Parse(cmd.ExecuteScalar().ToString());
    }
}

When I have breakpoint at line: return long.Parse(cmd.ExecuteScalar().ToString()); and I jump inside, there is a error:

"An unhandled exception of type 'System.NullReferenceException' occurred in Business.WeighingSystem.dll

Additional information: Object reference not set to an instance of an object."

I have really no idea, what object I don't have to set instance.

Thanks for every tip! :)

like image 680
Daniel Capek Avatar asked Sep 09 '26 13:09

Daniel Capek


1 Answers

It seems you are trying to return the number of rows affected by the command. In this case you need to use ExecuteNonQuery instead:

return long.Parse(cmd.ExecuteNonQuery());

Based on MSDN:

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

like image 135
Salah Akbari Avatar answered Sep 11 '26 07:09

Salah Akbari