开发者

backup restore sql database through AttachDBFilename

I am not able to create a backup of database saved in location like C:\database\mydb.mdf

error : Unable to create a backup

        Backup sqlBackup = new Backup();

        sqlBackup.Action = BackupActionType.Database;
        sqlBackup.BackupSetDescription = "ArchiveDataBase:" +
                                         DateTime.Now.ToShortDa开发者_如何学编程teString();
        sqlBackup.BackupSetName = "Archive";

        sqlBackup.Database = databaseName;

        BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
        //ServerConnection connection = new ServerConnection(serverName, userName, password);
        ServerConnection connection = new ServerConnection(serverName);

        Server sqlServer = new Server(connection);

        Database db = sqlServer.Databases[databaseName];

        sqlBackup.Initialize = true;
        sqlBackup.Checksum = true;
        sqlBackup.ContinueAfterError = true;

        sqlBackup.Devices.Add(deviceItem);
        sqlBackup.Incremental = false;

        sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
        sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

        sqlBackup.FormatMedia = false;

        sqlBackup.SqlBackup(sqlServer);   

 string dataBaseName = @"C:\database\mydb.mdf";    
 string serverName = @"Data Source=.\SQLEXPRESS;Integrated Security=True;User Instance=True";    
 string destinationPath = "C:\\mydb.bak";    

Maybe I am passing wrong variables?

Please can anyone verify it and post me the right solution

thnx in advance.

PS: database is not password protected and can use mixed authentication


First of all - I guess some of your parameters are wrong:

ServerConnection connection = new ServerConnection(serverName);

Here, you need to pass just the server's name - so in your case, do not send in your whole connection string - just .\SQLExpress

As for your database name - I don't know if you can use SMO to backup an "attached" MDF file in SQL Server - normally, this would be the database name (the name of the database only - no file name, no extension) when the database is on the server.

string dataBaseName = @"C:\database\mydb.mdf";    

So my suggestion here would be:

  • attach this MDF file to your SQL Server instance (which you have installed anyway)
  • give it a meaningful name, e.g. mydb
  • then use just the database name as your value here:

    string dataBaseName = "mydb";      
    

With these points in place, your code does work just fine in my case, at least...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜