通过DeriveParameters设置存储过程的参数

大多数的SqlHelper类封装了常见的数据库操作,但是有一点不爽的事,得到一个SqlCommand之后要一个一个设置参数,比如下图:
 这样的确是很郁闷呀,幸好SqlCommandBuilder有个静态的方法:
public static void DeriveParameters(SqlCommand command);
 使用这个方法有两个局限性:
  1.必须是SqlCommand
  2.只能是存储过程
 同时还要注意的事,在使用的时候,数据库连接必须是打开的。
好的,下面看看如何使用这个方法设置存储过程的参数:
方法的实现如下:
public static Collection<IDataParameter> GetParameters(IDbCommand command, object objParam)
        {
            Collection
<IDataParameter> collection = new Collection<IDataParameter>();
            
if (objParam != null)
            {
                PropertyInfo[] properties 
= objParam.GetType().GetProperties();
                SqlCommandBuilder.DeriveParameters((SqlCommand)command);

                int index = 0;
                foreach (SqlParameter parameter in command.Parameters)
                {
                    
if (parameter.ParameterName == "@RETURN_VALUE")
                    {
                        collection.Add(parameter);
                        
continue;
                    }
                   
foreach (PropertyInfo property in properties)
                    {
                        
if (("@" + property.Name.ToLower()) == parameter.ParameterName.ToLower())
                        {
                            parameter.Value 
= property.GetValue(objParam, null);
                            collection.Add(parameter);
                            
break;
                        }
                        index
++;
                    }
                    index 
= 0;
                }
                command.Parameters.Clear();
            }
            
return collection;
        }
如何使用呢:
   假设我们有如下存储过程:
   
ALTER PROCEDURE pro_Test
(
  @Gender bit,
  @City nvarchar(
50),
  @ID 
int output
)
AS
    
SET NOCOUNT ON
    select 
* from Club_Users where Gender=@Gender and City=@City
    
set @ID=1
    select @ID
    RETURN
   使用代码:
    现在我们来得到一个上面这个存储过程的Command
        public static IDbCommand GetStoredProcCommand(string commandText,object objParams)
        {
            IDbConnection connection 
= new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
            IDbCommand command 
= new SqlCommand();
            command.Connection 
= connection;
            command.CommandText 
= commandText;
            command.CommandType 
= CommandType.StoredProcedure;
            connection.Open();
            
foreach (var item in SqlHelper.GetParameters(command, objParams))
            {
                command.Parameters.Add(item);
            }
            
return command;
        }
   程序中调用便是这样:
   
            IDbCommand command = GetStoredProcCommand("pro_test"new { Gender = 1, City = "上海", ID = 0 });

            command.Connection.Close();
其中代码中的  new { Gender = 1, City = "上海", ID = 0 }  匿名类型就是设置存储过程中参数的值了。
 设置断点监视得到的Command的参数如下:

  











当然你可以把这些代码整合到你的SqlHelper中,同时也可以缓存那些参数,提高系能
posted @ 2009-08-03 23:38  MicroCoder  阅读(1968)  评论(2编辑  收藏  举报