简体   繁体   中英

Error inserting row into MS Access DB programmatically (C#)

I have a Microsoft Access database (*.mdb file) which I need to insert rows into programmatically (in C#). I have no control over this access file - it is a pre-existing file which I need to work with.

When I attempt this using the code below, a System.Data.OleDb.OleDbException is thrown. The message in that exception contains the same text that has been defined as the validation text for one of the fields (Customer). So on the surface, the exception message would indicate that I'm either not providing a required field, or that I'm providing an invalid value for that field.

However, the value I'm passing in should be Ok. Certainly, inserting a row with the same values inside of Access itself works fine.

The code I'm using is:

using (var connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Temp\\Indial_Reg.mdb;"))
{
    connection.Open();
    using (var cmd = new OleDbCommand("INSERT INTO [Indial Register] ([Exchange],[Customer]) Values ('WISB/SYRA','TEST')", connection))
    {
        try
        {
            cmd.ExecuteNonQuery();
        }
        catch (OleDbException e)
        {
        }
    }
}

Interestingly, when I open Microsoft Access and issue the exact same INSERT INTO command inside the access script editor, the insertion works flawlessly.

In case it is relevant, the validation rule which has been defined on the Customer field is : Like " [AZ] "

Am I using the wrong connection string? Wrong provider driver? Can anyone point me towards something I'm doing wrong in the code? I'm at my wits end. Any assistance would be fantastic.

My environment is: Windows 7 32 bit. I have MS Access 2007 installed. My code is running in Visual Studio 2012.

Thanks.

The problem is that the validation rule that you are having now doesn't permit value from your application.

The validation rule you required is this :

Like "%[A-Z]" Or Like "*[A-Z]"

The Rule "%[AZ]" will permit characters between A to Z from application

And

The Rule "*[AZ]" permits that from Access

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM