posts - 432,  comments - 40,  views - 55万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
复制代码

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);     

备份的路径必须写全了,连文件名也写进去,要不就会出现权限问题了.
复制代码
posted on   小石头的一天  阅读(137)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2020-08-01 安装Chrome插件网下载的.CRX格式插件安装时提示程序包无效:“CRX_HEADER_INVALID”的解决方法
2019-08-01 sqlserve 数据库8G log文件也有10来g 按日期删除 方法
点击右上角即可分享
微信分享提示