You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio 2013本地数据库C# Insert语句无报错但不生效

解决LocalDB中Insert语句无报错但不生效的问题

我来帮你排查这个在LocalDB开发里挺常见的问题,核心原因主要有两个:

1. 错误使用ExecuteReader()执行Insert操作

你的代码里用SqlDataReader reader = cmdDataBase.ExecuteReader();来执行Insert语句,这是不合适的。ExecuteReader()是专门用来读取Select语句返回的结果集的方法,虽然它不会抛出错误,但对于Insert/Update/Delete这类不需要返回结果集的操作,应该用ExecuteNonQuery()——它会返回受影响的行数,能直接帮你确认操作是否真的执行成功。

修改后的代码示例:

try {
    constring = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
    conDataBase = new SqlConnection(constring);
    SqlCommand cmdDataBase = new SqlCommand("INSERT INTO invoice (customer,date,type,totalBill,printedBy) VALUES ('2','12/12/18','Credit','6000','1');", conDataBase);
    
    conDataBase.Open();
    // 替换为ExecuteNonQuery获取受影响行数
    int affectedRows = cmdDataBase.ExecuteNonQuery();
    if(affectedRows > 0){
        MessageBox.Show("Record Saved Successfully", "SavedSuccessfully");
    } else {
        MessageBox.Show("No record was inserted", "Warning");
    }
    conDataBase.Close();
} catch (Exception ex) {
    MessageBox.Show(ex.ToString(), "Error");
}

2. LocalDB的|DataDirectory|复制陷阱

这是最容易踩的坑:当你在Visual Studio中运行项目时,项目根目录的KhalidDatabase.mdf会被自动复制到输出目录(比如bin\Debug或bin\Release)。你的代码连接的是输出目录里的数据库文件,但你在VS的SQL查询标签中操作的是项目根目录下的原始文件——这就导致你以为Insert没生效,实际上数据已经插入到了输出目录的数据库里,只是你查错了文件。

解决步骤:

  • 右键项目中的KhalidDatabase.mdf文件,选择属性
  • 将复制到输出目录的选项从始终复制改为如果较新则复制或者不复制
  • 之后去输出目录(比如bin\Debug)找到对应的KhalidDatabase.mdf,用VS打开它就能看到插入的记录了

额外优化建议

为了避免后续踩坑,还可以做这些优化:

  • 使用参数化查询,既避免SQL注入风险,也能规避日期、字符串格式等问题:
SqlCommand cmdDataBase = new SqlCommand("INSERT INTO invoice (customer,date,type,totalBill,printedBy) VALUES (@customer,@date,@type,@totalBill,@printedBy);", conDataBase);
cmdDataBase.Parameters.AddWithValue("@customer", "2");
cmdDataBase.Parameters.AddWithValue("@date", DateTime.Parse("12/12/18"));
cmdDataBase.Parameters.AddWithValue("@type", "Credit");
cmdDataBase.Parameters.AddWithValue("@totalBill", 6000);
cmdDataBase.Parameters.AddWithValue("@printedBy", "1");
  • 使用using语句自动释放数据库连接,避免连接泄漏:
using(SqlConnection conDataBase = new SqlConnection(constring)){
    conDataBase.Open();
    // 执行命令的代码
}

内容的提问来源于stack exchange,提问作者Sohaib Mughal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:24:48