Insert problems to .sdf database C#

2019-09-19 17:37发布

问题:

When i run the program it doesn't seem to have any errors but it doesn't insert any data to the database. Is there some essential code missing?

Here's my code:

            Using string connection = @"Data Source=|DataDirectory|\InvoiceDatabase.sdf";
            SqlCeConnection cn = new SqlCeConnection(connection);

            try
            {
                cn.Open();
            }
            catch (SqlCeException ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.ExitThread();
            }

            SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Client(Name, Address, Postcode, Telephone_Number)VALUES(@name, @address, @postcode, @tel)", cn);
            cmd.Parameters.AddWithValue("@name", txt_ClientName.Text);
            cmd.Parameters.AddWithValue("@address", txt_ClientAddress.Text);
            cmd.Parameters.AddWithValue("@postcode", txt_postcode.Text);
            cmd.Parameters.AddWithValue("@tel", txt_TelNo.Text);

            try
            {
                int affectedRows = cmd.ExecuteNonQuery();

                if (affectedRows > 0)
                {
                    txt_ClientAddress.Text = "";
                    txt_ClientName.Text = "";
                    txt_postcode.Text = "";
                    txt_TelNo.Text = "";
                    MessageBox.Show("Client: " + txt_ClientName.Text + " added to database. WOoo", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Client: " + txt_ClientName.Text + " Failed to add to database. WOoo", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

Thanks in advance for any feedback.

回答1:

Please make sure that you watch the database where you add the rows.

In most cases, the database .sdf file gets copied to the release folder and you work on that, while the server explorer has opened some other database file.

Try and open the .sdf file under Release, check if rows where added there.