开发者

Can't commit changes to SQL Server Compact Edition database

开发者 https://www.devze.com 2023-04-03 16:41 出处:网络
I have a problem, private void button_Submit_Click(object sender, EventArgs e) { try { string c开发者_如何学PythononnectionString = @\"Data Source=Database_TouchPOS.sdf;Persist Security Info=False;\"

I have a problem,

private void button_Submit_Click(object sender, EventArgs e)
{
   try
   {
      string c开发者_如何学PythononnectionString = @"Data Source=Database_TouchPOS.sdf;Persist Security Info=False;";
      using (SqlCeConnection connection = new SqlCeConnection(connectionString))
      {
         using (SqlCeCommand command = connection.CreateCommand())
         {
            connection.Open();
            command.CommandText = "INSERT INTO Product (Title,Price,Category_Id) VALUES (@title, @price,@category_Id)";
            command.Parameters.AddWithValue("@title", textBox_Title.Text);
            command.Parameters.AddWithValue("@price", textBox_Price.Text);
            command.Parameters.AddWithValue("@category_Id", comboBox_Category.SelectedIndex);

            command.ExecuteNonQuery();

            MessageBox.Show("Product Added Successfully...");
         }
         connection.Close();
      }                
   }
   catch (SqlException ex)
   {
      MessageBox.Show(ex.Message);
   }
}

Everything seem to be fine, but still can't add data into database.

  1. I did try with complete database path, example c:\project\database.sdf
  2. I did a lot of search before asking. I saw similar problems but not even a single one works for me.
  3. Data are added when compiling but not committed to database. I can see the data after second attempt of debugging.
  4. Please kindly try to explain in detail.

Thanks


You are probably facing this, http://erikej.blogspot.com/2010/05/faq-why-does-my-changes-not-get-saved.html suggest you use a full path to your database file in your connection string.


Did you try to use transactions explicitly?

IDbTransaction transaction = connection.BeginTransaction();
//add to database
transaction.Commit(); // before close connection


This is a very old thread, so I don't know if it will help anyone if I put my answer.

I had this problem, too. When I executed an update or insert code in C#, apparently, everything was ok, but when I looked up the database, there was no change.

The thing was that while debugging I had the database opened in a Management Studio. And somehow this obstructed the database changes even when there was no error message. Closing the Management Studio and opening it after executing the code, the changes where perfectly stored in the data base.

Regards.


complete example for those seeking like me... @"Data Source=C:\Users\MYPC\Documents\Visual Studio 2010\Projects\MyProjectFolder\MyProject-1\bin\Debug\MyDatabase.sdf;Persist Security Info=False;";

thank for this example. This saved my day.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号