Insert problems to .sdf database C#

风流意气都作罢 提交于 2019-12-13 07:54:02

问题


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.



来源:https://stackoverflow.com/questions/15663344/insert-problems-to-sdf-database-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!