Search code examples
vb.netsql-server-express

saving record in VB.NET


Thank you for checking my code

No matter what I do, the record is not saved, it does not give any error

I copied the database file from another project to the root of my project

I have a function called fill, which then saves the information from the select database, the moment I save it, it displays the new record in the datagrid, but when I open the program again, it does not show the record, and when I check the table itself, nothing is saved.

This is my code :

Dim con1 As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirector  y|anbar.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
 con1.Open()
 Dim com As New SqlCommand("INSERT INTO tblcustomer(name)Values(@name)", con1)
 com.Parameters.AddWithValue("name", txtName.Text)
 com.CommandType = CommandType.Text
 com.ExecuteNonQuery()
con1.Close()

Thank you for your advice.


Solution

  • The question in the comments is relevant: what value is returned ExecuteNonQuery? I'm confident that the answer is going to be 1, which means that everything is working exactly as it's supposed to and you just don't know how local data files work.

    When you add a data file to your project - MDF, MDB, ACCDDB or the like - it becomes a source file, i.e. part of the project. When you build your project, the compiled EXE is saved to the output folder and the data file is copied there too. It is that copy that your app connects to at run time.

    By default, the source file is copied to the output folder EVERY TIME you build your project. That means that if you run the project, make changes to the database, stop the project, make a code change and then run the project again, your database changes will be overwritten, like you never made them.

    It's important that you have these two copies of the database because you don't want to have to clean all your test data out when it comes time to release the application. You want to just build and get a clean database, which is exactly what happens.

    The solution to your "problem" is to select the data file in the Solution Explorer, open the Properties window and change the Copy to Output Directory property to Copy if Newer. That way, the working data file in the output folder will only be overwritten if you have made changes to the source file. That way, changes you make to the database will persist until you change the source data, delete the working data file or change that property again.