如何从VS创建的.mdf数据库进行备份

时间:2012-02-29 11:06:29

标签: c# backup sql-server-express

我使用vs 2010创建了一个.mdf数据库文件。我可以检索并将数据插入到数据库中,但是当我想要备份错误时,我已经处理了。该数据库未在Management Studio中附加。

我的代码:

SqlConnection connect;
connect = new SqlConnection(DAL.AccessLayerClass._connectionStr);
connect.Open();
SqlCommand command;
command = new SqlCommand(@"backup database AGMDB to disk ='d:\svBackUp1.bak' with init,stats=10",connect);
command.ExecuteNonQuery();
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);

我的连接字符串:

string _connectionStr = "Data Source=.\\SQLEXPRESS; AttachDbFilename=" + System.Windows.Forms.Application.StartupPath + "\\Database\\AGMDB.mdf; Integrated Security=True; Connect Timeout=30; User Instance=True;";

并且发生了错误:

Could not locate entry in sysdatabases for database 'AGMDB'. No entry found with that name. Make sure that the name is entered correctly.
BACKUP DATABASE is terminating abnormally.

我该如何解决这个错误? 感谢

1 个答案:

答案 0 :(得分:3)

你需要[]围绕DBFileName,试试这个:

SqlConnection connect;
connect = new SqlConnection(DAL.AccessLayerClass._connectionStr);
connect.Open();
SqlCommand command;
command = new SqlCommand(@"backup database [" + System.Windows.Forms.Application.StartupPath + "\\Database\\AGMDB.mdf] to disk ='d:\svBackUp1.bak' with init,stats=10",connect);
command.ExecuteNonQuery();
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);

参考:How to Backup and Restore SQL Express 2005 (AttachDbFilename mode)