问题
I have written the following function meant to update a student in my database:
public bool UpdateStudent(Student stu)
{
Console.WriteLine("StudentManger.UpdateStudent): Called");
int rowsChanged = 0;
using (var cnn = new SqlConnection(
Properties.Settings.Default.universityConnectionString))
{
using (var cmd = new SqlCommand("UPDATE Student " +
"SET FirstName = @FirstName, " +
"lastName = @LastName, " +
"birth = @birth " +
"WHERE id = @id", cnn))
{
cmd.Parameters.Add(new SqlParameter("@FirstName", stu.FirstName));
cmd.Parameters.Add(new SqlParameter("@LastName", stu.LastName));
cmd.Parameters.Add(new SqlParameter("@id", stu.ID));
cmd.Parameters.Add(new SqlParameter("@birth", stu.Birth));
cnn.Open();
rowsChanged = (int)cmd.ExecuteNonQuery();
Properties.Settings.Default.Save();
}
}
Properties.Settings.Default.Save();
return (rowsChanged != 0);
}
But when I call function no data is actually getting saved to the Database
Can someone tell me why?
回答1:
With the entire solution and information you provided in chat, your code is fine. The problem is that the .mdf database file is set to "Copy to Output Directory": "Always" in your project. Change this property to "Copy if newer" (or "Do not copy" and move it to the bin folder yourself) and it will not overwrite your changes when you re-run the application. Importantly, you will not see the changes you make in your application reflected in your .mdf database file in the project's root directory. It actually gets copied to the /bin folder and that's where the changes are persisted. So, if you don't change the "Copy to Output Directory" property, it will copy from your root to your /bin folder every time you build. Thus it appears that the changes aren't being persisted, when they actually are.
来源:https://stackoverflow.com/questions/10729953/rows-not-being-updated