Strong Coders Community

Where the extreme coders hang out.
Welcome to Strong Coders Community Sign in | Join | Help Messenger
in Search

Generic ExecuteScalar method

Last post 01-28-2007, 4:05 PM by Ryan Olshan . 0 replies.
Sort Posts: Previous Next
  •  01-28-2007, 4:05 PM 1677
    • Ryan Olshan is not online. Last active: 02-09-2007, 10:44 PM Ryan Olshan
    • Top 10 Contributor
      Male
    • Joined on 11-14-2005
    • Virginia, USA
    • Posts 383
    • Points 14,040
    • MicrosoftMVP Moderator StrongCoders

    Generic ExecuteScalar method

    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
    Filed under: ADO.NET , ExecuteScalar , .NET Generics
    • Post Points: 5
    • Alert the moderators

Powered by Community Server (Commercial Edition), by Telligent Systems