1

我遇到了与 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);
}
4

2 回答 2

3

您没有与 关联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带有连接和命令的语句,以确保连接对象的处置。

于 2013-11-08T14:49:39.673 回答
0

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

command1.Connection=connection1 ;
于 2013-11-08T14:51:20.043 回答