public void AddProductClass(string sC_Title,string sC_ID)
        {
            //定义数据库的Connection and Command 
            SqlConnection myConnection = new SqlConnection(SQLHelp.DBConnectionString);
            if (sC_ID == "")
            {
                SqlCommand myCommand = new SqlCommand("AddProductClass", myConnection);                //定义访问数据库的方式为存储过程
                myCommand.CommandType = CommandType.StoredProcedure;                .......
            }
            else
            {
                SqlCommand myCommand = new SqlCommand("AddSubProductClass", myConnection);                //定义访问数据库的方式为存储过程
                myCommand.CommandType = CommandType.StoredProcedure;                .......            }
                //打开数据库的连接
                myConnection.Open();
                        
                //执行数据库的存储过程(访问数据库)
                myCommand.ExecuteNonQuery();
            
                if (myConnection.State == ConnectionState.Open)
                {
                    //关闭数据库的连接
                    myConnection.Close();
                }
            
            //return (string)paramCache[0].Value;
        }执行结果为什么提示--当前上下文中不存在名称“myCommand”//执行数据库的存储过程(访问数据库)
myCommand.ExecuteNonQuery();

解决方案 »

  1.   

    public void AddProductClass(string sC_Title,string sC_ID)
    {
      //定义数据库的Connection and Command
      SqlConnection myConnection = new SqlConnection(SQLHelp.DBConnectionString);
      SqlCommand myCommand;                      // <------------------- 注意这里
      if (sC_ID == "")
      {
        myCommand = new SqlCommand("AddProductClass", myConnection);    //定义访问数据库的方式为存储过程
        myCommand.CommandType = CommandType.StoredProcedure;    .......
      }
      else
      {
        myCommand = new SqlCommand("AddSubProductClass", myConnection);    //定义访问数据库的方式为存储过程
        myCommand.CommandType = CommandType.StoredProcedure;    .......  }
      //打开数据库的连接
      myConnection.Open();  //执行数据库的存储过程(访问数据库)
      myCommand.ExecuteNonQuery();  if (myConnection.State == ConnectionState.Open)
      {
        //关闭数据库的连接
        myConnection.Close();
      }  //return (string)paramCache[0].Value;
    }
      

  2.   

    要把 SqlCommand myCommand; 的定义放到 if-else 的外面, 否则出了 if-else 的范围, myCommand 就无定义了, 所以 myCommand.ExecuteNonQuery(); 会出错.
      

  3.   

    谢谢 wuyi8808(空间/IV) ,问题解决!!!