[英]Why doesn't my C# code update the SQL Server database although I get the correct number of affected rows
I created the following code: 我创建了以下代码:
public static bool setHeadword(int id, string headword)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\pms.mdf;Integrated Security=True";
conn.Open();
SqlCommand command = new SqlCommand("UPDATE headwords SET Headword = @headword WHERE Id = @id", conn);
command.Parameters.AddWithValue("@headword", headword);
command.Parameters.AddWithValue("@id", id);
int result = command.ExecuteNonQuery();
conn.Close();
return true;
}
But the code doesn't work because the value in the database doesn't change. 但是代码不起作用,因为数据库中的值没有更改。 If I run the code manually in the database the change takes place.
如果我在数据库中手动运行代码,则会发生更改。 But it won't work with C#.
但是它不适用于C#。
Also the result variable are holding the right number of affected rows (1 in this case). 同样,结果变量保留正确数量的受影响的行(在这种情况下为1)。
I'm not sure I have to flush the changes or something else. 我不确定是否必须清除更改或其他内容。
Thanks for your help and best regards Franz 感谢您的帮助和最诚挚的问候Franz
static void Update(int id, string headword)
{
try
{
//You should create connectionString with correct details otherwise fail connection
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE headwords SET Headword=@headword" +
" WHERE Id=@Id", conn))
{
cmd.Parameters.AddWithValue("@Id", id);
cmd.Parameters.AddWithValue("@headword", headword);
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Handle sql Exception
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.