数据库不存在错误

3
当我备份数据库时,出现一个错误提示说数据库不存在,但我可以成功附加数据库,其他进程如数据插入和更新也正常工作。但是当我备份数据库时,会出现以下错误。
我展示了错误截图和备份按钮代码。
string cnstr="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\fees_data.mdf;Integrated Security=True;User Instance=True;"



SqlConnection connect;
        connect = new SqlConnection(cnstr);
        connect.Open();
        if (txtdname.Text == "")
        { dname = "Default.bak"; }
        else
        { dname = txtdname.Text + ".bak"; }
        SqlCommand command;
        command = new SqlCommand(@"backup database fees_data to disk ='c:\DATABackup\" + dname + "'", connect);
        command.ExecuteNonQuery();
        connect.Close();

当我点击备份按钮时,出现以下错误信息:
“数据库 'fees_data' 不存在,请确保名称输入正确。 备份数据库异常终止。”

这将在您确认数据库名称和路径而没有任何代码错误的情况下工作,只需检查您存储备份文件的数据库名称和路径即可。 - AB Vyas
2个回答

3

数据库名称可能与.mdf文件名不同。

运行此查询时会得到什么结果?

select name from sys.databases;

从中选择正确的名称。


1
代替这段代码。
SqlCommand command;
   command = new SqlCommand(@"backup database fees_data to disk ='c:\DATABackup\" + dname + "'", connect);
   command.ExecuteNonQuery();

使用下面编写的代码。
string fullPath= "";
 string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
 fullPath= (System.IO.Path.GetDirectoryName(executable));
 AppDomain.CurrentDomain.SetData("DataDirectory", fullPath);
 fullPath=fullPath+"\\fees_data.mdf";

 SqlCommand command;
 command = new SqlCommand(@"backup ['"+fullPath+"'] to disk ='c:\DATABackup\" + dname + "'", connect);
 command.ExecuteNonQuery();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接