Microsoft Access UPDATE command using C# OleDbConnection and Command NOT working

谁都会走 提交于 2019-11-26 22:06:55

问题


I'm using Microsoft Access unfortunately because of higher forces and trying to update a record with no luck.

This is the code:

private void UpdateContact(Contact contact)
{
    using (OleDbConnection db = new OleDbConnection(_connString))
    {
        string query = "UPDATE [Contact] SET [FirstName] = @FirstName, [LastName] = @LastName, [MobileNumber] = @MobileNumber WHERE [Id] = @Id";

        OleDbCommand cmd = new OleDbCommand(query, db) { CommandType = CommandType.Text };
        cmd.Parameters.AddWithValue("@Id", contact.Id);
        cmd.Parameters.AddWithValue("@FirstName", contact.FirstName);
        cmd.Parameters.AddWithValue("@LastName", contact.LastName);
        cmd.Parameters.AddWithValue("@MobileNumber", contact.MobileNumber);

        db.Open();

        int rowsAffected = cmd.ExecuteNonQuery();

        db.Close();
    }
}

Everything seems to be fine, no exception but no rowsAffected either. It always returns 0. I have checked the values while debugging and its the correct that should persist. The access file created with MS Access 2007 but its type is of 2002-2003.

Any idea what am I doing wrong?


回答1:


try

string query = "UPDATE [Contact] SET [FirstName] = ? [LastName] = ?, [MobileNumber] = ? WHERE [Id] = ?"

Add your parameters in the order of the statement, i.e. firstname...id




回答2:


You need ? for the place holder and the parameters must be added in the order in which they occur: http://msdn.microsoft.com/en-us/library/dw70f090.aspx



来源:https://stackoverflow.com/questions/4589348/microsoft-access-update-command-using-c-sharp-oledbconnection-and-command-not-wo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!