ExecuteNonQuery返回“连接属性尚未初始化”

本文关键字:初始化 属性 返回 连接 ExecuteNonQuery | 更新日期: 2023-09-27 18:06:16

我使用的是VS2010和SQL Server 2008 Management Studio

protected void btnsave_click(object sender, EventArgs e)
{
    SqlConnection myConnection = new SqlConnection("Data Source=SAAD-CH-HP;Initial Catalog=ovms;Integrated Security=True;");
    myConnection.Open();
    SqlCommand cmd = new SqlCommand(@"INSERT INTO request(reqtype, source,employeeID, vehID, destination) VALUES ('" 
    + official + "','" + source + "','" + emp_id + "','" + DropDownList1 + "','" + destination + "')");
    cmd.ExecuteNonQuery();
    myConnection.Close();
}

当我运行程序时,出现了这个异常

ExecuteNonQuery: Connection property has not initialized.

ExecuteNonQuery返回“连接属性尚未初始化”

您没有将命令与连接关联。

您需要使用连接句柄向SqlCommand构造函数添加另一个参数。

请将您的代码更新如下。设置SQLCommand的连接属性。

protected void btnsave_click(object sender, EventArgs e)
        {
            SqlConnection myConnection = new SqlConnection("Data Source=SAAD-CH-HP;Initial Catalog=ovms;Integrated Security=True;");
            myConnection.Open();
            SqlCommand cmd = new SqlCommand(@"INSERT INTO request(reqtype, source,employeeID, vehID, destination) VALUES ('" + official + "','" + source + "','" + emp_id + "'," + DropDownList1.Text + ",'" + destination + "')");
            cmd.Connection = myConnection;
            cmd.ExecuteNonQuery();
            myConnection.Close();
        }

或在SQL Test之后的构造中添加myConnection

SqlCommand cmd = new SqlCommand(@"INSERT INTO request(reqtype, source,employeeID, vehID, destination) VALUES ('" + official + "','" + source + "','" + emp_id + "'," + DropDownList1.Text + ",'" + destination + "')",myConnection);