6

The manual says that the ExecuteScalar method should be used like:

public T ExecuteScalar<T>( 
   string commandText,
   CommandType commandType,
   params DbParameter[] parameters
)

But how do I create that array of parameters? I need to provide my stored procedure 2 parameters.

dtb
  • 213,145
  • 36
  • 401
  • 431
Tys
  • 3,592
  • 9
  • 49
  • 71
  • Can you provide a link to that manual? [DbCommand.ExecuteScalar](http://msdn.microsoft.com/en-us/library/system.data.common.dbcommand.executescalar.aspx) has no parameters. – dtb Aug 17 '11 at 18:38

5 Answers5

9
  • DbParameter is an abstract class.
  • Since the type T can not be inferred from the usage, you have to specify it.
  • Althought you can just pass a variable number of parameters without creating the array, if you are dynamically creating a variable number of parameters, the array is your friend.

    var parameters = new[]{
                new SqlParameter(){ ParameterName="foo", Value="hello" },
                new SqlParameter(){ ParameterName="bar", Value="World" }
            };
    x.ExecuteScalar<int>(commandText, commandType, parameters);
    
Juan Ayala
  • 3,388
  • 2
  • 19
  • 24
  • both answers work fine, but i prefer this one a bit more that the other. Thanks everyone! – Tys Aug 17 '11 at 19:54
4

The parameters parameter has the params keyword. This means that you don't have to create the array explicitly but can pass a variable number of arguments to the method:

x.ExecuteScalar(commandText, commandType, parameter1, parameter2);

However, if you want, you can create the array explictly and pass it to the method as follows:

DbParameter[] parameters = new DbParameter[] { parameter1, parameter2 };

x.ExecuteScalar(commandText, commandType, parameters);
dtb
  • 213,145
  • 36
  • 401
  • 431
3

DbParameter is an abstract class - but you can instantiate the derived type.

If you are using Sql server it is SqlParameter:

 DbParameter[] parameters = new DbParameter[2]; 
 parameters[0]  = new SqlParameter("param1",  123456);
 parameters[1]  = new SqlParameter("param2",  "abcdef");
stevieg
  • 652
  • 4
  • 14
alexm
  • 6,854
  • 20
  • 24
1

The params keyword means that you can specify a varying number of parameters (so from 1 to [pretty much] infinity).

You can just call the method like this: ExecuteScalar<SomeType>("Command!", CommandType.SomeCommandType, dbParameter1, dbParameter2);

chrischu
  • 3,047
  • 3
  • 27
  • 44
0

In a "perfect world" you should create any single parameter by this code:

DbProviderFactory f = DbProviderFactories.GetFactory("System.Data.SqlClient");
DbParameter parameter = f.CreateParameter();

but you probably have to use some specific platform functionality that SqlParameter implements... as SqlCommand does: SqlCommand.Parameters.AddWithValue() etc.

Massimo
  • 137
  • 1
  • 4