【问题标题】:ExecuteNonQuery- Connection property has not been initializedExecuteNonQuery - 连接属性尚未初始化
【发布时间】:2013-11-08 14:48:09
【问题描述】:

我遇到了与 MS Access 的 OleDb 连接问题。此行抛出错误:

command1.ExecuteNonQuery();

下一部分是我的代码:

if (textBox.Text.Length != 6) return;
{
    cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =@Name");
    cmd.Parameters.Add(new SqlParameter("Name", textBox.Text.Replace(@"L", "")));
    cmd.CommandType = CommandType.Text;
    cmd.Connection = DBConnection;

    returnValue = cmd.ExecuteScalar() + "\t " + textBox.Text.Replace(@"L", "");

    DBConnection.Close();

    OleDbConnection connection1 = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Registration.accdb");
    OleDbCommand command1 = new OleDbCommand();
    command1.CommandText = "UPDATE Table SET ID=@ID, Name=@Name, TimeIn=@TimeInAM, TimeOut=@TimeOutAM";
    command1.Parameters.AddWithValue("@ID", returnValue);
    connection1.Open();
    command1.ExecuteNonQuery();
    connection1.Close();

    Staff_Register(returnValue, e);
}

【问题讨论】:

    标签: c# ms-access oledb


    【解决方案1】:

    您没有将connection1command1 关联,这就是您收到异常的原因。

    command1.CommandText = "UPDATE Table SET ID=@ID, Name=@Name, TimeIn=@TimeInAM, TimeOut=@TimeOutAM";
    command1.Parameters.AddWithValue("@ID", returnValue);
    command1.Connection = connection1; // missing this
    connection1.Open();
    

    还可以考虑将using 语句与连接和命令一起使用,以确保处理连接对象。

    【讨论】:

      【解决方案2】:

      在调用 ExecuteNonQuery() 之前将连接对象分配给您的命令对象,如下所示:

      command1.Connection=connection1 ;
      

      【讨论】:

        猜你喜欢
        • 2012-05-03
        • 2011-07-22
        • 2012-08-20
        • 1970-01-01
        • 2013-03-28
        相关资源
        最近更新 更多