In a continuation of cool things we've done with generics, I'll share my generic ExecuteScalar method for the MS SQL Server .NET provider.
public
static
T ExecuteScalar(
string
commandText,
string
connectionString)
{
return
ExecuteScalar(commandText, connectionString,
null
);
}
public
static
T ExecuteScalar(
string
commandText,
string
connectionString,
params
SqlParameter
[] parameters)
{
T result =
default
(T);
if
(!
string
.IsNullOrEmpty(commandText))
{
using
(
SqlConnection
connection =
new
SqlConnection
(connectionString))
{
using
(
SqlCommand
command =
new
SqlCommand
(commandText, connection))
{
if
(parameters !=
null
&& parameters.Length > 0)
{
foreach
(
SqlParameter
parameter
in
parameters)
{
command.Parameters.Add(parameter);
}
}
connection.Open();
result = (T)command.ExecuteScalar();
connection.Close();
}
}
}
return
result;
}
Ryan Olshan
Microsoft MVP, ASP.NET
Blog
|
Group
|
Website
|
Strong Coders Community