Add SqlParameter to SqlCommand : SqlParameter « ADO.Net « C# / CSharp Tutorial






using System;        
using System.Drawing;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;

public class MainClass
{
  [STAThread]
  static void Main() 
  {
    string cstr = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;";
    using ( SqlConnection conn = new SqlConnection( cstr ) )
    {
      conn.Open();

      string selstr = "select FirstName from Employee where lastname = @name";
      SqlCommand cmd = new SqlCommand( selstr, conn );
      SqlParameter name = cmd.Parameters.Add( "@name", SqlDbType.NVarChar, 15 );
      name.Value = "Tang";
      SqlDataReader rdr = cmd.ExecuteReader();

      if ( rdr.Read() )
      {
        Console.WriteLine(rdr.GetString( 0 ) );
      }
      else
      {
        Console.WriteLine("not available yet" );
      }
    }

  }
}








32.24.SqlParameter
32.24.1.Pass value to SqlCommand with SqlParameter
32.24.2.Add SqlParameter to SqlCommand
32.24.3.Command Parameter
32.24.4.Passing a Null Value to a Query Parameter