我遇到了与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);
}
答案 0 :(得分:3)
您没有将connection1
与command1
相关联,这就是您获得例外的原因。
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
语句与连接和命令一起使用,以确保处理连接对象。
答案 1 :(得分:0)
在调用ExecuteNonQuery()之前将连接对象分配给命令对象,如下所示:
command1.Connection=connection1 ;