Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why saving changes to a database fails?

I have following C# code in a console application.

Whenever I debug the application and run the query1 (which inserts a new value into the database) and then run query2 (which displays all the entries in the database), I can see the new entry I inserted clearly. However, when I close the application and check the table in the database (in Visual Studio), it is gone. I have no idea why it is not saving.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string fileName = "FlowerShop.sdf";
                string fileLocation = "|DataDirectory|\\";
                DatabaseAccess dbAccess = new DatabaseAccess();
                dbAccess.Connect(fileName, fileLocation);

                Console.WriteLine("Connected to the following database:\n"+fileLocation + fileName+"\n");
                string query = "Insert into Products(Name, UnitPrice, UnitsInStock) values('NewItem', 500, 90)";
                string res = dbAccess.ExecuteQuery(query);
                Console.WriteLine(res);

                string query2 = "Select * from Products";
                string res2 = dbAccess.QueryData(query2);
                Console.WriteLine(res2);
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.ReadLine();
            }
        }
    }

    class DatabaseAccess
    {
        private SqlCeConnection _connection;

        public void Connect(string fileName, string fileLocation)
        {
            Connect(@"Data Source=" + fileLocation + fileName);
        }

        public void Connect(string connectionString)
        {
            _connection = new SqlCeConnection(connectionString);
        }

        public string QueryData(string query)
        {
            _connection.Open();
            using (SqlCeDataAdapter da = new SqlCeDataAdapter(query, _connection))
            using (DataSet ds = new DataSet("Data Set"))
            {
                da.Fill(ds);
                _connection.Close();
                return ds.Tables[0].ToReadableString(); // a extension method I created
            }
        }

        public string ExecuteQuery(string query)
        {
            _connection.Open();
            using (SqlCeCommand c = new SqlCeCommand(query, _connection))
            {
                int r = c.ExecuteNonQuery();
                _connection.Close();
                return r.ToString();
            }
        } 
    }

EDIT: Forgot to mention that I am using SQL Server Compact Edition 4 and VS2012 Express.

like image 739
Joe Slater Avatar asked Jun 17 '13 12:06

Joe Slater


People also ask

How do I enable the option to prevent saving changes in SQL Server?

Open SQL Server Management Studio (SSMS). On the Tools menu, click Options. In the navigation pane of the Options window, click Designers. Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

What is the impact of dropping a database?

Dropping a database deletes the database from an instance of SQL Server and deletes the physical disk files used by the database. If the database or any one of its files is offline when it is dropped, the disk files are not deleted. These files can be deleted manually by using Windows Explorer.


1 Answers

It is a quite common problem. You use the |DataDirectory| substitution string. This means that, while debugging your app in the Visual Studio environment, the database used by your application is located in the subfolder BIN\DEBUG folder (or x86 variant) of your project. And this works well as you don't have any kind of error connecting to the database and making update operations.

But then, you exit the debug session and you look at your database through the Visual Studio Server Explorer (or any other suitable tool). This window has a different connection string (probably pointing to the copy of your database in the project folder). You search your tables and you don't see the changes.

Then the problem get worse. You restart VS to go hunting for the bug in your app, but you have your database file listed between your project files and the property Copy to Output directory is set to Copy Always. At this point Visual Studio obliges and copies the original database file from the project folder to the output folder (BIN\DEBUG) and thus your previous changes are lost.

Now, your application inserts/updates again the target table, you again can't find any error in your code and restart the loop again until you decide to post or search on StackOverflow.

You could stop this problem by clicking on the database file listed in your Solution Explorer and changing the property Copy To Output Directory to Copy If Newer or Never Copy. Also you could update your connectionstring in the Server Explorer to look at the working copy of your database or create a second connection. The first one still points to the database in the project folder while the second one points to the database in the BIN\DEBUG folder. In this way you could keep the original database ready for deployment purposes and schema changes, while, with the second connection you could look at the effective results of your coding efforts.

EDIT Special warning for MS-Access database users. The simple act of looking at your table changes the modified date of your database ALSO if you don't write or change anything. So the flag Copy if Newer kicks in and the database file is copied to the output directory. With Access better use Copy Never.

like image 90
Steve Avatar answered Sep 19 '22 08:09

Steve