I've checked other Stack Overflow questions to find answers, but I just can't find a solution to this. I am trying to insert string data into a SQL CE (local database).
I can read from the database, but I cannot insert data, regardless of whether I hard-code it or try to add it with parameters.
The table to be modified is called users
. It has 3 columns: ID
, name
, email
.
Here is the code I am using:
string connection = Properties.Settings.Default.LocalDBConnectionString;
using (var con = new SqlCeConnection(connection))
{
con.Open();
// (I also tried adding with parameters but couldn't get it working.)
using (var com = new SqlCeCommand("INSERT INTO users (name, email) " +
"VALUES (N'jimmy', N'email@jim.com')", con))
{
int numRowsAffected = com.ExecuteNonQuery();
// This returns '1 row affected' but doesn't actually update the database
Console.WriteLine(numRowsAffected);
Console.ReadKey();
}
}
Although the Console outputs 1
, because 1 row is affected, when I go back into the database and check, it has not inserted the new data.
I was following this tutorial, but only the Read works, the Insert or write doesn't work.
I also found this similar Stack Overflow question, but using parameters, still couldn't get it to work.
Edit:
My connection string is:
Data Source=|DataDirectory|\LocalDB.sdf
I don't know how to find the Build Settings, it is a Local Database I created within the console application solution, It is stored in the project directory.
I am in "Debug" configuration if that helps?
Here is another example I found on the internet:
SqlCeConnection con = new SqlCeConnection(Properties.Settings.Default.LocalDBConnectionString);
con.Open();
SqlCeCommand comInsert = new SqlCeCommand ("INSERT INTO users(name, email) VALUES('value 1', 'value 2')", con);
comInsert.ExecuteNonQuery();
SqlCeCommand comSelect = new SqlCeCommand("SELECT * FROM users", con);
SqlCeDataReader reader = comSelect.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0} {1}", reader["name"], reader["email"]);
Console.ReadKey();
}
con.Close();
I just copied and pasted this in, and changed the main variables. This example temporarily inserts the data, but when I go to Visual Studio's Server Explorer and view the table, it hasn't updated.