2

我正在使用 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:连接属性尚未初始化。

4

2 回答 2

1

您尚未将命令与连接关联。

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

于 2013-03-27T21:15:53.333 回答
0

请在下面更新您的代码。设置 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 测试之后的构建中,添加 myConnection

SqlCommand cmd = new SqlCommand(@"INSERT INTO request(reqtype, source,employeeID, vehID, destination) VALUES ('" + official + "','" + source + "','" + emp_id + "'," + DropDownList1.Text + ",'" + destination + "')",myConnection);
于 2013-03-27T21:17:04.633 回答