我在向访问数据库中插入记录时遇到了很大困难。我在访问中尝试了查询,它插入正常。我也在查询构建器中尝试了查询,它也可以工作但是如果我运行此代码它声称已将记录插入数据库,但是当我检查数据库时没有新记录的迹象。
oleDbCommandCreateAppointment.Parameters["appointmentDate"].Value = "06/04/2012";
oleDbCommandCreateAppointment.Parameters["timeSlotID"].Value ="21";
oleDbCommandCreateAppointment.Parameters["startTime"].Value = "09:00";
oleDbCommandCreateAppointment.Parameters["employeeID"].Value ="1";
oleDbCommandCreateAppointment.Parameters["clientID"].Value ="1";
oleDbCommandCreateAppointment.Parameters["assistantID"].Value ="1";
oleDbCommandCreateAppointment.Parameters["appointmentType"].Value = "Quote";
oleDbCommandCreateAppointment.Parameters["appointmentFlag"].Value = "Booked";
try
{
oleDbConnection.Open();
int rows = oleDbCommandCreateAppointment.ExecuteNonQuery();
MessageBox.Show("Rows inserted " + rows.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
oleDbConnection.Close();
}
SQL命令
INSERT INTO tblAppointments
(appointmentDate, timeSlotID, startTime, employeeID, clientID, assistantID, appointmentType, appointmentFlag)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
非常感谢
答案 0 :(得分:3)
您需要将连接与db命令对象关联:
oleDbConnection.Open();
oleDbCommandCreateAppointment.Connection = oleDbConnection;
int rows = oleDbCommandCreateAppointment.ExecuteNonQuery();
击> <击> 撞击>
编辑 - 这个可能与参数排序有关,试试这个:
oleDbCommandCreateAppointment.Parameters[0].Value = "06/04/2012";
oleDbCommandCreateAppointment.Parameters[1].Value = "21";
oleDbCommandCreateAppointment.Parameters[2].Value = "09:00";
oleDbCommandCreateAppointment.Parameters[3].Value = "1";
oleDbCommandCreateAppointment.Parameters[4].Value = "1";
oleDbCommandCreateAppointment.Parameters[5].Value = "1";
oleDbCommandCreateAppointment.Parameters[6].Value = "Quote";
oleDbCommandCreateAppointment.Parameters[7].Value = "Booked";
注意 - 我在处理这个时学到的东西,你不能在ODBC和OleDB命令中使用命名参数,只能使用位置参数(参见Table 6),这个链接指出OleDbCommand个对象仅在命令类型为Text
时支持位置参数。位置参数依赖于顺序。