November 2003
Intermediate to advanced
476 pages
14h 38m
English
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.
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.