Updating Data

Like TextReader and XmlReader, DataReader provides a read-only, forward-only view of the underlying data stream. This means that updating a database requires a new IDbCommand and the ExecuteNonQuery( ) method, which I mentioned earlier.

Example 11-2 shows a program to insert a new coupon into the database.

Example 11-2. Program to insert a new coupon into a database
using System;
using System.Data.SqlClient;

public enum DiscountType {
  Percentage,
  Fixed
}

public class AddCoupon {
  public static void Main(string [ ] args) {
    SqlConnection connection = new SqlConnection(
      "Initial Catalog=AngusHardware; User ID=sa");

    SqlCommand command = new SqlCommand(
      "insert into coupons ( coupon_code, discount_amount, discount_type, expiration_date ) " +
      "values ( '077GH', 15, " + (int)DiscountType.Percentage + 
      ", '11/30/2002' )", connection);

    connection.Open( );

    command.ExecuteNonQuery( );

    connection.Close( );
  }
}

The SqlCommand.ExecuteNonQuery( ) method simply executes the SQL command without expecting any values to be returned. If you’re familiar with SQL, this insert statement should need no explanation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.243.184