using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
public void BackupDatabase(SqlConnectionStringBuilder csb, string backupPath)
{
// 创建服务器连接对象
ServerConnection connection = new ServerConnection(csb.DataSource, csb.UserID, csb.Password);
try
{
// 连接到服务器
Server server = new Server(connection);
// 创建备份对象
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.Database = csb.InitialCatalog;
// 设置备份路径
BackupDeviceItem backupDevice = new BackupDeviceItem(backupPath, DeviceType.File);
backup.Devices.Add(backupDevice);
// 执行备份操作
backup.SqlBackup(server);
}
catch (Exception ex)
{
// 处理异常
Console.WriteLine("备份数据库出错:" + ex.Message);
}
finally
{
// 关闭连接
connection.Disconnect();
}
}
public void RestoreDatabase(SqlConnectionStringBuilder csb, String backUpFile)
{
ServerConnection connection = new ServerConnection(csb.DataSource, csb.UserID, csb.Password);
Server sqlServer = new Server(connection);
Restore rstDatabase = new Restore();
rstDatabase.Action = RestoreActionType.Database;
rstDatabase.Database = csb.InitialCatalog;
BackupDeviceItem bkpDevice = new BackupDeviceItem(backUpFile, DeviceType.File);
rstDatabase.Devices.Add(bkpDevice);
rstDatabase.ReplaceDatabase = true;
rstDatabase.SqlRestore(sqlServer);
}
string saveAway = uiTBBackupDirectory.Text.Trim()+ "\\xxxx.bak"; string ConnectionString = ConfigurationManager.ConnectionStrings["SqlConnectionStr"].ToString(); string[] cons = ConnectionString.Split(';'); string[] databases = cons[3].Split('=');
把上边的字符串划分字段改改整到下边的配置内,下边为测试数据
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
csb.ConnectionString = ConnectionString;
csb.DataSource = ".,1933";
csb.InitialCatalog = "xxxx";
csb.UserID = "sa";
csb.Password = "125612";
bakHelper.BackupDatabase(csb, saveAway);
备份的路径必须写全了,连文件名也写进去,要不就会出现权限问题了.
技术交流qq群:143280841