Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I insert data into local database (SQL Compact Edition) with C#?

Tags:

c#

database

I am doing a project on Visual Studio. I am using a local database (empty sql server compact edition). I chose Dataset and created my table (Images). It has a primary autoincrement id column, and an nvarchar ImagePath column. I want to insert data in it and here is my code.

SqlCeConnection con = new SqlCeConnection();
con.ConnectionString = yeniApplicationDatabase.Properties.Settings.Default.DatabaseEdaConnectionString;
con.Open();
using (SqlCeCommand com = new SqlCeCommand("INSERT INTO Images (ImagePath) VALUES ('book')", con))
{
  com.ExecuteNonQuery();
}

I don't know why but this one doesn't give any error, the syntax(SQL) is fine. However, when I check the table data, it is still null. Here is the thing;

In the same run,
I execute that code, then I execute another one which is select * from images...
It shows 'book'. But still, the table data is empty, and when I rerun it without inserting, only selecting from Images, it is gone again. I really don't understand what is going on. Why can't I put anything in my database?

I also added con.Close() but it still doesn't work.

like image 419
Ada Avatar asked Jun 27 '26 17:06

Ada


1 Answers

SqlCeConnection con = new SqlCeConnection();
con.ConnectionString =  yeniApplicationDatabase.Properties.Settings.Default.DatabaseEdaConnectionString;
con.Open();
SqlCeCommand com = new SqlCeCommand("INSERT INTO Images (ImagePath) VALUES ('book')", con);

com.ExecuteNonQuery();


com.Dispose();
con.Close();

Closing the connection should complete the insert.

EDIT: update on the solution

Which database file(.sdf) are you viewing to check whether the data has been inserted. check the content of the test table in the .sdf in the bin\Debug folder. I believe that your data is inserted properly in the database file which exist in bin\Debug folder.

Just found a similar question on stack overflow: Why can't I insert a record into my SQL Compact 3.5 database? and I firmly believe that your problem is exactly the same. you are checking the wrong database file.

like image 112
reggie Avatar answered Jun 29 '26 07:06

reggie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!