C# sqlCommand和以编程方式检索和设置存储过程的参数

C# sqlCommand和以编程方式检索和设置存储过程的参数,c#,.net,ado.net,C#,.net,Ado.net,我刚接触.NET,但需要在深水区游泳一会儿。我的任务是扩展一个现有的单元测试,该测试目前只尝试接收所有存储过程的列(作为测试db连接完整性和其中模式的一种方法)。目标是检索所有存储过程的参数,并尝试使用空值运行它们,测试以验证是否没有返回任何记录集。我一直在拼命尝试使用ADO.NET来提高速度,但我一辈子都不知道如何做到这一点。这是我所知道的(有点断章取义)。测试抱怨没有传入任何参数,但我认为我是在将现有参数集设置为null,然后简单地将其传回 // bind our sql schema g

我刚接触.NET,但需要在深水区游泳一会儿。我的任务是扩展一个现有的单元测试,该测试目前只尝试接收所有存储过程的列(作为测试db连接完整性和其中模式的一种方法)。目标是检索所有存储过程的参数,并尝试使用空值运行它们,测试以验证是否没有返回任何记录集。我一直在拼命尝试使用ADO.NET来提高速度,但我一辈子都不知道如何做到这一点。这是我所知道的(有点断章取义)。测试抱怨没有传入任何参数,但我认为我是在将现有参数集设置为null,然后简单地将其传回

 // bind our sql schema gridview
foreach (SqlSchemaItem item in items)
   {
 // pull a connection
 using (var sqlConnection = new SqlConnection(connectionString))
 {
     // open connection
     sqlConnection.Open();

     // get schema
     try
     {
        /*
         * Part 1 - test that the schema is ok...
         */
            var sqlCommand = new SqlCommand(item.ObjectName, sqlConnection);
            sqlCommand.CommandType = CommandType.StoredProcedure;
            SqlCommandBuilder.DeriveParameters(sqlCommand);
            sqlCommand.ExecuteReader(CommandBehavior.SchemaOnly);

            // success to console
            Console.WriteLine(item.ObjectName + " is ok.");

        /*
         * Part 2 - test that the stored procedure does not return any data.
         */

        // set all the parameters to NULL
        foreach (SqlParameter parameter in sqlCommand.Parameters)
        {
            if (parameter.Direction == ParameterDirection.Input || parameter.Direction == ParameterDirection.InputOutput)
            {
               parameter.Value = null;
               Console.WriteLine("Parameter {0} set to null", parameter.ParameterName, parameter.Value);
            }
         }

         var temp = sqlCommand.ExecuteReader(CommandBehavior.SingleResult);
         if (temp.HasRows) {
             Console.WriteLine(string.Format("A record was returned in {0} with value {0}", temp.GetName(0), temp.GetString(0)));
         }
         else {
            Console.WriteLine("No result was returned");
          }
         Console.WriteLine(" ");
         }
    catch ...
    finally ...
    etc.

使用
DBNull.Value
而不是
null

你试过DbNull.Value而不是null吗?打得好,谢谢。(见下面我的回答)啊,答对了。我认为我的语法(或方法)是错误的,我没有想到我的null值实际上可能不是null。