“executiontenonquery连接属性尚未初始化”

时间:2013-04-06 16:02:03

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

SqlConnection cn = new SqlConnection(@"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******");

SqlCommand cmd = new SqlCommand();
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=@finish where Name='" + Name + "'";
cmd.Parameters.Add(new SqlParameter("@finish", finish));
cmd.ExecuteNonQuery();
cmd.Clone();

错误消息

  

尚未初始化Executenonquery连接属性。

2 个答案:

答案 0 :(得分:3)

您当前代码的问题在于您尚未设置Connection对象的SqlCommand属性。试试这个,

SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;

您还必须参数化name

上设置的值
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=@finish where Name=@name";
cmd.Parameters.Add(new SqlParameter("@finish", finish));
cmd.Parameters.Add(new SqlParameter("@name", Name));

完整代码

string finish = DropDownListFi.SelectedValue;
String Name = Request.QueryString["Name"];
string connStr = @"DataSource=dbedu.cs.vsb.cz\SQLDB;
                   Persist Security Info=True;
                   User ID=*****;
                   Password=*******";
string sqlStatement = @"UPDATE navaznost_ukolu 
                        SET    finish = @finish 
                        WHERE  Name = @Name";

using (SqlConnection conn = new SqlConnection(connStr))
{
    using(SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = conn;
        cmd.CommandText = sqlStatement;
        cmd.CommandType = CommandType.Text;

        cmd.Parameters.Add(new SqlParameter("@finish", finish));
        cmd.Parameters.Add(new SqlParameter("@name", Name));

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch(SqlException e)
        {
            // do something with the exception
            // do not hide it
            // e.Message.ToString()
        }
    }
}

正确编码

  • 使用using语句进行propr对象处理
  • 使用try-catch块来正确处理对象

答案 1 :(得分:2)

错误是不言自明的,您尚未分配与命令的连接。您可以使用构造函数:

using(var cn = new SqlConnection(@"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******"))
using(var cmd = new SqlCommand(
    "UPDATE navaznost_ukolu SET finish=@finish where Name=@Name"
    , cn))
{
   string finish = DropDownListFi.SelectedValue;
   cn.Open();
   String Name = Request.QueryString["Name"];
   cmd.Parameters.AddWithValue("@finish", finish);
   cmd.Parameters.AddWithValue("@Name", Name);
   cmd.ExecuteNonQuery();
}

请注意,我还为Nameusing语句使用了sql参数,以确保实现IDisposable的任何内容都被处理掉,即使出现异常也是如此。这也将关闭连接。