Reputation: 2139
I am trying to write a common Save function and I am using Dbcommand
. My code is:
private static int Save(CommandType commandtype, string commandText, SqlParameter[] commandParameters, bool p)
{
int id = -1;
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandType = commandtype;
command.CommandText = commandText;
foreach(SqlParameter pa in commandParameters)
{
command.Parameters.Add(pa);
}
connection.Open();
id = command.ExecuteNonQuery();
}
}
return id;
}
Where am I going wrong? The code saves the value in the database.
Upvotes: 2
Views: 7351
Reputation: 1413
Please delete the line in the SP SET NOCOUNT ON; in the SP so you will get the value
Upvotes: 5
Reputation: 1138
Execute Scalar returns only 1 row..and executenonquety returns affected rows only... ExecuteNonQuery doesnt give u return values...
Upvotes: -1
Reputation: 4114
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. look at msdn
But I don't understand what do you mean when you said that the method ExecuteNonQuery should return value. If you want to return a value you should use the ExecuteScalar
Upvotes: 2
Reputation: 103525
ExecuteNonQuery
returns the number of rows affected.
If your SQL statement is something like
insert into ... values ...
select @@identity
Then you need to use ExecuteScalar
instead.
Upvotes: 2