con.open有错误。我有一个连接错误,我的代码看起来像这样

时间:2011-08-31 08:22:08

标签: c# asp.net sql-server-2008

 if (lblevent.Text == Request.QueryString["name"])
 {  
      string EventName = Request.QueryString["name"];
      const string SQL = "SELECT SMS FROM Event WHERE EventName = @EventName";

      using (SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true"))
      using (SqlCommand Command = new SqlCommand(SQL, con))
           Command.Parameters.Add("@EventName", EventName);                      
           {
                con.Open();//at here the "con" has an error it says:"'con' does not exist on current context."
           }
 }

实际上我已经在上面的代码中声明了一个sqlconnection(con)int但它没有读取它。请有人帮忙..谢谢

2 个答案:

答案 0 :(得分:3)

这是问题所在:

using (SqlConnection con = new SqlConnection("..."))
using (SqlCommand Command = new SqlCommand(SQL, con))
 Command.Parameters.Add("@EventName", EventName);
{
    con.Open();
    ...
}

这相当于:

using (SqlConnection con = new SqlConnection("..."))
{
    using (SqlCommand Command = new SqlCommand(SQL, con))
    {
        Command.Parameters.Add("@EventName", EventName);
    }
}
{
    con.Open();
    ...
}

此时我希望显而易见的是 - 当你致电con.Open时,你不再在using声明中。你想要:

using (SqlConnection con = new SqlConnection("..."))
using (SqlCommand Command = new SqlCommand(SQL, con))
{
    Command.Parameters.Add("@EventName", EventName);                      
    con.Open();
    ...
}

答案 1 :(得分:1)

也许你应该添加括号。

if (lblevent.Text == Request.QueryString["name"])
            {  
       string EventName = Request.QueryString["name"];
                const string SQL = "SELECT SMS FROM Event WHERE EventName = @EventName";
                using (SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true"))
                  {
                   using (SqlCommand Command = new SqlCommand(SQL, con))
                     {
                      Command.Parameters.Add("@EventName", EventName);                      
                      con.Open();//at here the "con" has an error it says:"'con' does not exist on current context."
                     }
                  }
             }