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

本文关键字:连接 属性 executenonquery 初始化 | 更新日期: 2023-09-27 18:07:53

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连接属性未初始化

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

当前代码的问题是您没有设置SqlCommand对象的Connection属性。试试这个,

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语句进行适当的对象处理
  • 使用try-catch块来正确处理对象

这个错误是不言自明的,您没有将连接分配给命令。您可以使用构造函数:

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的内容都被处理掉,即使在出现异常的情况下。这也将关闭连接。