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

LocalDB数据库备份不含数据的问题解决方案咨询

如何生成包含数据的LocalDB数据库备份?

问题描述

我有一个名为golds.mdf的LocalDB数据库,执行备份操作时流程正常,但生成的备份文件不含任何数据。

连接字符串

<add name="cs" connectionString="Data Source(LocalDB)\MSSQLLocalDB;AttachDbFilename='|DataDirectory|\golds.mdf';Integrated Security=True"/>

备份代码

DateTime date1 = DateTime.Today;

var calendar = new System.Globalization.PersianCalendar();
int year = calendar.GetYear(date1);
int month = calendar.GetMonth(date1);
int day = calendar.GetDayOfMonth(date1);
string date12 = string.Format(string.Format("{0}-{1}-{2}", year, month, day));
// string mybackup = "GolShop";
if (BackupPath.Text == string.Empty)
{
    MessageBox.Show("لطفا موقعیت نسخه را انتخاب کنید");
}
else
{
    int r = 0;
    string cmd = "BACKUP DATABASE golds TO Disk =  '" + BackupPath.Text + "\\" + "Dataase" + "-" + date12 + ".bak'";
    r = database.setData(cmd);
  
    database.closeConnection();
    this.Enabled = false;
    this.Enabled = true;

    MessageBox.Show("Backup done.....");
}

解决方法

  • 确认备份的数据库名称正确:LocalDB通过AttachDbFilename附加的数据库,逻辑名称不一定是golds。打开SQL Server Management Studio连接到(LocalDB)\MSSQLLocalDB实例,在对象资源管理器中找到目标数据库,右键查看属性确认其真实数据库名称,替换备份命令中的golds。
  • 显式指定数据库名称:修改连接字符串,添加Initial Catalog=golds,确保数据库以指定名称附加,避免SQL Server生成随机逻辑名称:
    <add name="cs" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='|DataDirectory|\golds.mdf';Initial Catalog=golds;Integrated Security=True"/>
    
  • 修正备份命令的拼写与路径:命令中Dataase是拼写错误,应改为Database;使用Path.Combine拼接路径避免字符串拼接错误,同时改用参数化查询规避SQL注入风险:
    string backupPath = Path.Combine(BackupPath.Text, $"Database-{date12}.bak");
    string cmd = "BACKUP DATABASE golds TO Disk = @BackupPath";
    // 根据你的database类实现参数化传递@BackupPath
    
  • 验证数据库数据存在:通过SSMS连接到目标数据库,确认表中确实存在数据,排除数据库本身无数据的情况。
  • 检查备份执行结果:利用database.setData(cmd)的返回值r判断备份命令是否执行成功,避免流程正常但命令实际失败的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:33:22