Pass value to SqlCommand with SqlParameter : SqlParameter « ADO.Net « C# / CSharp Tutorial






using System;
using System.Data;
using System.Data.SqlClient;

class MainClass
{
    public static void Main()
    {
        using (SqlConnection con = new SqlConnection())
        {
            con.ConnectionString = @"Data Source = .\sqlexpress;Database = Northwind; Integrated Security=SSPI";
            con.Open();
            
            string employeeID =  "5";
            string title = "Cleaner";
            
            using (SqlCommand com = con.CreateCommand())
            {
                com.CommandType = CommandType.Text;
                com.CommandText = "UPDATE Employee SET Title = @title" +
                    " WHERE Id = @Employeeid";
    
                // Create a SqlParameter object for the title parameter.
                SqlParameter p1 = com.CreateParameter();
                p1.ParameterName = "@title";
                p1.SqlDbType = SqlDbType.VarChar;
                p1.Value = title;
                com.Parameters.Add(p1);
    
                // Use a shorthand syntax to add the id parameter.
                com.Parameters.Add("@Employeeid", SqlDbType.Int).Value = employeeID;
    
                // Execute the command and process the result.
                int result = com.ExecuteNonQuery();
    
                if (result == 1)
                {
                    Console.WriteLine("Employee {0} title updated to {1}.",
                        employeeID, title);
                }
                else
                {
                    Console.WriteLine("Employee {0} title not updated.",
                        employeeID);
                }
            }
        }
    }
}








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