SQL Compact Edition Insert C#
I am trying to inse开发者_运维知识库rt some values into a SQL CE database like this and nothing happens. What I do wrong?
string strConn = Properties.Settings.Default.SqlConnectionString;
using (SqlCeConnection con = new SqlCeConnection(strConn))
{
con.Open();
using (SqlCeCommand cmd = new SqlCeCommand("insert into CustTable(ID, Name) values (@Val1, @val2)", con))
{
cmd.Parameters.AddWithValue("@Val1", customer.ID);
cmd.Parameters.AddWithValue("@Val2", customer.Name);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
}
How are you "trying to insert some values..."? Are you running the app from Visual Studio? Why do you think "nothing happens"? Are you opening your original .sdf file after running your app?
Examine the Copy File property for the database file in Solution Explorer; is it "Copy"? That means Visual Studio will create a copy of the original database file in your bin folder and set the connection string to that path. All changes happen to the copy, and if you examine the original file it will be unchanged.
There is another SO question with the same problem; see if that helps.
Looks like you forgot to open the connection first - try this:
using (SqlCeConnection con = new SqlCeConnection(strConn))
{
con.Open();
using (SqlCeCommand cmd = new SqlCeCommand("insert into CustTable(ID, Name) values (@Val1, @val2)",con))
{
cmd.Parameters.AddWithValue("@Val1", customer.ID);
cmd.Parameters.AddWithValue("@Val2", customer.Name);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
}
Try this.
using (SqlCeConnection con = new SqlCeConnection(strConn))
{
SqlCeParameter par;
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "insert into CustTable(ID, Name) values (@Val1, @val2)";
// Create the parameters
par = new SqlCeParameter("@Val1", SqlDbType.Int);
cmd.Parameters.Add(par);
par = new SqlCeParameter("@Val2", SqlDbType.NChar, 50);
cmd.Parameters.Add(par);
// Set the values
cmd.Parameters["@Val1"].Value = customer.ID;
cmd.Parameters["@Val2"].Value = customer.Name;
cmd.ExecuteNonQuery();
// Dispose
cmd.Dispose();
}
精彩评论