Monday, February 17, 2014

Everything is fine but oledbCommand does not work with MS Access database

While working MS Access and vb.net together, i found a small limitation of OLEDB provider.

Please consider the following scene:
cmd.CommandText = "UPDATE [Contacts] SET [FirstName] = @FirstName, [LastName] = @LastName, [Mobile] = @Mobile, [Email] = @Email, [City] = @City WHERE [Id] = @Id"

cmd.Parameters.AddWithValue("@Id", Id)
cmd.Parameters.AddWithValue("@FirstName", FirstName)
cmd.Parameters.AddWithValue("@LastName", LastName)
cmd.Parameters.AddWithValue("@Mobile", Mobile)
cmd.Parameters.AddWithValue("@Email", Email)
cmd.Parameters.AddWithValue("@City", City)

cmd.ExecuteNonQuery()

Everything is right but still record will not be updated. Why?

Answer: Please, go through the order of parameters in SQL Statement and order of parameters declared in vb.net. Parameter "Id" is last in SQL where as first in vb.net code. There it mess up. Rule is, Order of parameters defined in SQL must be same as Order of parameters declared in vb.net.

The following way-

cmd.CommandText = "UPDATE [Contacts] SET [FirstName] = @FirstName, [LastName] = @LastName, [Mobile] = @Mobile, [Email] = @Email, [City] = @City WHERE [Id] = @Id"

cmd.Parameters.AddWithValue("@FirstName", FirstName)
cmd.Parameters.AddWithValue("@LastName", LastName)
cmd.Parameters.AddWithValue("@Mobile", Mobile)
cmd.Parameters.AddWithValue("@Email", Email)
cmd.Parameters.AddWithValue("@City", City)
cmd.Parameters.AddWithValue("@Id", Id)
cmd.ExecuteNonQuery()

Note: While working with sql Provider, you do not suffer with this limitation.

-Now it works. Hope you find this helpful.

No comments:

Post a Comment