逆水行船

别人的天堂,是我的异乡;无端的繁华,倍添我的惆怅

 

Attribute学习:AddCustomerCLS

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

namespace WebApplication1
{
 /// <summary>
 /// 属性的案例程序。
 /// </summary>
 public class AddCustomerCLS
 {
  public AddCustomerCLS()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }

  public int AddCustomer2(SqlConnection connection,
   string customerName,
   string country,
   string province,
   string city,
   string address,
   string telephone)
  {
   SqlCommand command=new SqlCommand("AddCustomer", connection);
   command.CommandType=CommandType.StoredProcedure;

   command.Parameters.Add("@CustomerName",SqlDbType.NVarChar,50).Value=customerName;
   command.Parameters.Add("@country",SqlDbType.NVarChar,20).Value=country;
   command.Parameters.Add("@Province",SqlDbType.NVarChar,20).Value=province;
   command.Parameters.Add("@City",SqlDbType.NVarChar,20).Value=city;
   command.Parameters.Add("@Address",SqlDbType.NVarChar,60).Value=address;
   command.Parameters.Add("@Telephone",SqlDbType.NVarChar,16).Value=telephone;
   command.Parameters.Add("@CustomerId",SqlDbType.Int,4).Direction=ParameterDirection.Output;

   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();

   int custId=(int)command.Parameters["@CustomerId"].Value;
   return custId;
  } 
 
  /// <summary>
  /// 该方法中用到存储过程。存储过程的名称,就是方法的名称。
  /// </summary>
  /// <param name="connection"></param>
  /// <param name="customerName"></param>
  /// <param name="country"></param>
  /// <param name="province"></param>
  /// <param name="city"></param>
  /// <param name="address"></param>
  /// <param name="telephone"></param>
  /// <param name="customerId"></param>
  [ SqlCommandMethod(CommandType.StoredProcedure) ]
  public void AddCustomer([NonCommandParameter]SqlConnection connection,
   [SqlParameter(50)] string customerName,
   [SqlParameter(20)] string country,
   [SqlParameter(20)] string province,
   [SqlParameter(20)] string city,
   [SqlParameter(60)] string address,
   [SqlParameter(16)] string telephone,
   out int customerId )
  {
   customerId = 0; // 需要初始化输出参数

   // 调用Command生成器生成SqlCommand实例,该command对象参数集合中的参数没有设置为任何类型。
   SqlCommand command = SqlCommandGenerator.GenerateCommand(connection, null, new object[]{customerName, country, province, city, address, telephone, customerId});
   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();

   // 必须明确返回输出参数的值
   customerId = (int)command.Parameters["@CustomerId"].Value;
  }

 }
}

posted on 2005-07-26 11:51  荣-  阅读(147)  评论(0编辑  收藏  举报

导航