c# - 为什么我的 C# 代码没有更新 SQL Server 数据库,尽管我得到了正确的受影响行数
问题描述
我创建了以下代码:
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;
}
但是代码不起作用,因为数据库中的值没有改变。如果我在数据库中手动运行代码,则会发生更改。但它不适用于 C#。
结果变量也持有正确数量的受影响行(在这种情况下为 1)。
我不确定我是否必须刷新更改或其他内容。
感谢您的帮助和最诚挚的问候弗朗茨
解决方案
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
}
}
推荐阅读
- outlook - 为什么我的 Microsoft 加载项突然停止在 F12 开发工具中显示为选项?
- firebase - ReferenceError:未定义章节
- java - 使用 JsonFlatener.flattenAsMap 时如何从键中获取索引?
- rust - 如何为多个向量创建一个 Rust 迭代器,将下一项作为元组返回?
- javascript - JavaScript 单选按钮不起作用,需要帮助
- reactjs - 如何关闭 MUI 数据表中的过滤器对话框
- java - 如何将 TelephonyManager 移动到不同的类然后 MainActivity
- azure - 使用现有令牌调用 Microsoft.Azure.Fluent API
- reactjs - 如何在 Typescript 中将类型传递给 React 上下文使用者
- sql - 删除所有以以下开头的行:INSERT INTO `mdl_logstore_standard_log` VALUES