用程序备份数据库
那位朋友做过用代码备份和还原数据库的程序?希望能跟我分享下……
程序代码:
(1)数据备份语句:backup database 数据库名 to disk='保存路径\db_Name.bak' (2)数据恢复语句:restore database 数据库名 from disk='保存路径\db_Name.bak' WITH MOVE 'dbName_Data' TO 'c:\tcomcrm20041217.mdf', --数据文件还原后存放的新位置 //数据库备份 private void btnBak_Click(object sender, EventArgs e) //备份 { string saveAway = this.tbxBakLoad.Text.ToString().Trim(); string cmdText = @"backup database " + System.Configuration.ConfigurationSettings.AppSettings["dbName"] + " to disk='" + saveAway + "'"; BakReductSql(cmdText,true); } //数据库还原 private void btnReduct_Click(object sender, EventArgs e) //还原 { string openAway = this.tbxReductLoad.Text.ToString().Trim();//读取文件的路径 string cmdText = @"restore database " + System.Configuration.ConfigurationSettings.AppSettings["dbName"] + " from disk='" + openAway + "'"; BakReductSql(cmdText,false); } /// <summary> /// 对数据库的备份和恢复操作,Sql语句实现 /// </summary> /// <param name="cmdText">实现备份或恢复的Sql语句</param> /// <param name="isBak">该操作是否为备份操作,是为true否,为false</param> private void BakReductSql(string cmdText,bool isBak) { SqlCommand cmdBakRst = new SqlCommand(); SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=master;uid=sa;pwd=;"); try { conn.Open(); cmdBakRst.Connection = conn; = CommandType.Text; if (!isBak) //如果是恢复操作 { string setOffline = "Alter database GroupMessage Set Offline With rollback immediate "; string setOnline = " Alter database GroupMessage Set Online With Rollback immediate"; = setOffline + cmdText + setOnline; } else { = cmdText; } cmdBakRst.ExecuteNonQuery(); if (!isBak) { MessageBox.Show("数据库还原成功", "系统消息"); } else { MessageBox.Show("备份成功", "系统消息"); } } catch (SqlException sexc) { MessageBox.Show("操作失败"); } catch (Exception ex) { MessageBox.Show("操作失败"); } finally { cmdBakRst.Dispose(); conn.Close(); conn.Dispose(); } }
[ 本帖最后由 wangnannan 于 2010-10-28 15:08 编辑 ]