Run an INSERT statement that uses parameters : SqlCommand Parameters « Database ADO.net « C# / C Sharp






Run an INSERT statement that uses parameters


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

class UsingParameters
{
  public static void Main()
  {
   SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");

    mySqlConnection.Open();

    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.CommandText =
      "INSERT INTO Employee (" +
      "  ID, FirstName, LastName" +
      ") VALUES (" +
      "  @ID, @FirstName, @LastName" +
      ")";

    mySqlCommand.Parameters.Add("@ID", SqlDbType.NChar, 2);
    mySqlCommand.Parameters.Add("@FirstName", SqlDbType.NVarChar, 10);
    mySqlCommand.Parameters.Add("@LastName", SqlDbType.NVarChar, 10);

    mySqlCommand.Parameters["@ID"].Value = "9";
    mySqlCommand.Parameters["@FirstName"].Value = "New";
    mySqlCommand.Parameters["@LastName"].IsNullable = true;
    mySqlCommand.Parameters["@LastName"].Value = "New";


    mySqlCommand.ExecuteNonQuery();
    Console.WriteLine("Successfully added row to Customers table");

    mySqlConnection.Close();
  }
}


           
       








Related examples in the same category