Question

Hi I have A local database named Database1.sdf. I´m accessing it with following code to insert some data into a table:

public string DoLocalDbCmd(string Command)
        {
            int NumeroAffetto;
            string ConnString = @"Data Source=|DataDirectory|\Database1.sdf";
            SqlCeConnection Conn = new SqlCeConnection(ConnString);
            SqlCeCommand Comando = new SqlCeCommand(Command, Conn);
            Comando.CommandType = System.Data.CommandType.Text;
            try
            {
                Comando.Connection.Open();
                NumeroAffetto = Comando.ExecuteNonQuery();
                return NumeroAffetto.ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                Comando.Connection.Close();
            }
        }

private void button1_Click(object sender, EventArgs e)
        {
            DoLocalDbCmd cmd = new DoLocalDbCmd();

            string cmdex = cmd.RunSqlCmd("insert into TBL_PROVA (BELLO) VALUES ('VERO')");

            MessageBox.Show(cmdex);
        }

The execution of code happen without errors, I retrieve the number of affected row = 1.

But after if I query the database there is not inserted no row.

Somebody can suggest to me what can be wrong ?

Thankyou in advance

Piercarlo

Was it helpful?

Solution

It is a common scenario when these conditions are all or partially present in your project.

  • You have a connection string with the DataDirectory substitution string.
  • You have a connection on the Server Explorer that point to an SDF file located in your project directory.
  • You have the property Copy To Output Directory set to Copy Always on your SDF file listed in your project items.

When you run the program inside the IDE of VS the SDF file present in your project folder is copied to the Output Directory (BIN\DEBUG) following the setting of Copy To Output Directory and this could result in the overwriting of the file eventually already present in BIN\DEBUG.
You run your code and insert correctly your data into the file in the BIN\DEBUG folder.
You stop your program and checks if the record is present using the Server Explorer and you don't see any new record because you are looking at the file in the Project Folder.
You start a new debug session and the file in the BIN\DEBUG is overwritten again with the empty one.

So... change the property Copy to the Output Directory to Copy Never to stop this copying, change the connection in the server explorer to point to your database in the BIN\DEBUG folder (Or add another one keeping the old one for schema changes and the new one to verify your DML operations)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top