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! :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With