使用c#和SQL Server备份附加的数据库文件(.mdf)

时间:2013-08-13 11:59:37

标签: c# .net sql sql-server winforms

我试图在Winforms应用程序中创建数据库的备份。但它不起作用

这是我的代码:

cn.Open();
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText=@"BACKUP DATABASE Database1.mdf TO DISK = 'C:\db1.bak'";
dr = cmd.ExecuteReader();
dr.close();
cn.Close();

此处cnSqlConnectioncmdSqlCommanddrSqlDataReader。请给我一个解决方案。

1 个答案:

答案 0 :(得分:2)

为什么不能使用sql server management objects

创建如下方法

using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

public void BackupDatabase(string databaseName, string userName, string password, string serverName, string destinationPath)
{
    //Define a Backup object variable.
    Backup sqlBackup = new Backup();

    //Specify the type of backup, the description, the name, and the database to be backed up.
    sqlBackup.Action = BackupActionType.Database;
    sqlBackup.BackupSetDescription = "BackUp of:" + databaseName + "on" + DateTime.Now.ToShortDateString();
    sqlBackup.BackupSetName = "FullBackUp";
    sqlBackup.Database = databaseName;

    //Declare a BackupDeviceItem
    BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + "FullBackUp.bak", DeviceType.File);
    //Define Server connection
    ServerConnection connection = new ServerConnection(serverName, userName, password);
    //To Avoid TimeOut Exception
    Server sqlServer = new Server(connection);
    sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
    Database db = sqlServer.Databases[databaseName];

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

    //Add the device to the Backup object.
    sqlBackup.Devices.Add(deviceItem);
    //Set the Incremental property to False to specify that this is a full database backup.
    sqlBackup.Incremental = false;

    sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
    //Specify that the log must be truncated after the backup is complete.
    sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

    sqlBackup.FormatMedia = false;
    //Run SqlBackup to perform the full database backup on the instance of SQL Server.
    sqlBackup.SqlBackup(sqlServer);
    //Remove the backup device from the Backup object.
    sqlBackup.Devices.Remove(deviceItem);
}

使用上面显示的名称空间。您必须添加这些命名空间的引用。为此 -

转到您的应用程序并右键单击References文件夹并选择Add Reference。

现在转到“浏览”标签,浏览以下路径 - “C:\ Program Files \ Microsoft SQL Server \ 100 \ SDK \ Assemblies”

现在选择以下dll

Microsoft.SqlServer.ConnectionInfo.dll, Microsoft.SqlServer.Management.Sdk.Sfc.dll, Microsoft.SqlServer.Smo.dll, Microsoft.SqlServer.SmoExtended.dll, Microsoft.SqlServer.SqlEnum.dll,

注意:根据MS SQL Server的版本,Dll的位置可能会延迟,我不确定。