SQL does not keep new recordings

Asked

Viewed 233 times

1

I’m using a Service-based Database (.MDF) to save some data from an application I’m developing. However, after I close the application, the data that was entered in the table disappears. It follows the code that I am using:

System.Data.SqlClient.SqlConnection sqlConnection1 =
        new System.Data.SqlClient.SqlConnection(@"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=|datadirectory|\Database2.mdf");
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
        cmd.CommandType = System.Data.CommandType.Text;
        sqlConnection1.Open();
        cmd.CommandText = @"INSERT INTO sistemas (nome, potnom, numcolun, colunpac, colunpcc, colunirrad, tempomed) VALUES ('"+ nome+ "','"+ potNom+"','"+ numcolun +"','"+ colunpac+"','" + colunpcc + "','" +colunirrad+"','" + tempoMed + "')";
        cmd.Connection = sqlConnection1;
        cmd.ExecuteNonQuery();
sqlConnection1.Close();

INSERT runs correctly, I can query the database if I don’t close the application, however, when restarting the application, the table comes back empty.

  • Make sure the . mdf file is not being recreated when initializing the application.

  • It was exactly that, and it was fixed with the Toncunha solution below. Thank you very much!

1 answer

1


For the information to remain in the database . mdf, you need to make a change to the file properties.

  1. Right click on the database found in the tab Solution Explorer;
  2. Go on properties;
  3. In the option Copy to Output Directory select Copy if newer

Alterando a propriedade do banco de dados

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.