how to execute multiple SQL statements using a SqlCommand object : SqlCommand Insert « ADO.Net « C# / CSharp Tutorial






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

class ExecuteMultipleSQL {
    public static void Main() {
        SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
        SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
        mySqlCommand.CommandText =
          "INSERT INTO Customers (CustomerID, CompanyName) " +
          "VALUES ('J5COM', 'Jason 5 Company');" +
          "SELECT CustomerID, CompanyName " +
          "FROM Customers " +
          "WHERE CustomerID = 'J5COM';" +
          "UPDATE Customers " +
          "SET CompanyName = 'ACompany' " +
          "WHERE CustomerID = 'J5COM';" +
          "SELECT CustomerID, CompanyName " +
          "FROM Customers " +
          "WHERE CustomerID = 'J5COM';";

        mySqlConnection.Open();

        SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
        do {
            while (mySqlDataReader.Read()) {
                Console.WriteLine("mySqlDataReader[0] = " + mySqlDataReader[0]);
                Console.WriteLine("mySqlDataReader[1] = " + mySqlDataReader[1]);
            }
            Console.WriteLine(""); // visually split the results
        } while (mySqlDataReader.NextResult());

        mySqlDataReader.Close();
        mySqlConnection.Close();
    }
}








32.20.SqlCommand Insert
32.20.1.Inserting Data Using SQLStatements
32.20.2.Execute nonquery to insert a record (row)
32.20.3.how to execute multiple SQL statements using a SqlCommand object
32.20.4.Command NonQuery