C# 将记录插入Access数据库

C# 将记录插入Access数据库,c#,sql,ms-access,insert,C#,Sql,Ms Access,Insert,我很难将记录插入access数据库。我在access中尝试了这个查询,结果很好。我也在query builder中尝试过该查询,它也可以工作。但是,如果我运行此代码,它会声称已将记录插入数据库,但当我检查数据库时,没有新记录的迹象 oleDbCommandCreateAppointment.Parameters["appointmentDate"].Value = "06/04/2012"; oleDbCommandCreateAppointment.Paramete

我很难将记录插入access数据库。我在access中尝试了这个查询,结果很好。我也在query builder中尝试过该查询,它也可以工作。但是,如果我运行此代码,它会声称已将记录插入数据库,但当我检查数据库时,没有新记录的迹象

      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        (?, ?, ?, ?, ?, ?, ?, ?)
非常感谢

您需要将连接与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命令,只能使用位置参数(请参见),此链接指出,当命令类型为
Text
时,对象仅支持位置参数。位置参数取决于顺序。

这样做了,但仍然有相同的问题。从您发布的代码来看,它看起来不像您发布的代码,您能否显示更多的代码,然后,命令对象的构造,等等。您是否正在打开事务而不提交它?对不起,我的意思是,我已经添加了您建议的内容。我的连接对象在表单的任务栏区域,我的插入命令也在表单的任务栏区域。您至少可以发布您的查询吗?连接字符串也是这样。参数存储在集合中,顺便说一下*您可能想尝试命名参数,而不是
。杰特应该明白你在做什么。也就是说,
插入到。。。值(@A、@B、@C)
,然后将命名参数(例如,
@clientID
)添加到您的
OleDbCommand
@ta.spect.is您不能将命名参数与OleDbCommand一起使用(我更新了我的答案,并说明了这一点,这也让我措手不及)@pstrjds我很确定JET的做法略有不同。你可以说
值(@A,@B,@A)
,你只需要按顺序添加
@A
@B
。@ta.speot.如果问题不在于底层引擎,你可以在Jet中使用命名值,他使用的是OleDB连接器,它只支持位置参数。我在回答中提供了一个链接。@pstrjds是的,我记得
Microsoft.Jet.OLEDB.4.0
当您通过
System.Data.OLEDB
使用它时,它支持命名参数。