MS Access DB doesnt save changes after execution (

2019-08-10 01:33发布

问题:

I have the following code for using an access database

 OleDbConnection con = new OleDbConnection(myproject.Properties.Settings.Default.myDBConnectionString);
 con.Open();
 OleDbCommand command = new OleDbCommand("INSERT INTO components (name) VALUES (@p_col1)", con);
 command.Parameters.Add("@p_col1", OleDbType.VarChar).Value = "test row";
 int rows = command.ExecuteNonQuery();

At this point rows value is 1 and when I make select queries after that the row inserted is available. The problem comes when the program finishes: in further executions that row isn´t there anymore.

I´ve tried with transactions

OleDbTransaction transaction = con.BeginTransaction();
command.Transaction = transaction;
transaction.Commit();

and using DataSets and ADO this way

//... add row to dataset ...
OleDbDataAdapter sda = new OleDbDataAdapter("select * from components", con);
OleDbCommandBuilder cb = new OleDbCommandBuilder(sda);

sda.Update(ds.Components); //tried with ds.Components.AcceptChanges(); before and after this line

but in every case i have the same problem, seems like the insert query is not done in the real database. Do you know why can this be happening???

Thanks in advance

回答1:

Is the database in your bin directory? Is it also part of your project? I have seen this happen when every time you build it overwrites the database in your bin directory with the one from the project directory, so it appears things are not getting saved.



回答2:

There may be more than one database and you are not inserting to the one you think you are inserting to.



回答3:

MS Visual Studio builds the Access DB into the product. --- The product is located in your bin directory. --- To view any and all changes to your DB via application use this one When you initially add the DB to the project, it is set to always update the product on build. This can be a good thing, but I find it rather annoying. In order to fix this: Select the MS Access DB from your Solution Explorer, Hit F4 to go to it's properties, Change the field "Copy to Output Directory" to "Copy if newer" instead of "Always".