using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SQLDMO;
//-------------注意引用了dll namespace 备份数据库
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// 选择备份位置
private void button3_Click(object sender, EventArgs e)
{
saveFileDialog1.ShowDialog();
textBox1.Text = saveFileDialog1.FileName;
}
//备份数据库
private void button1_Click(object sender, EventArgs e)
{
string dbname = textBox2.Text;
string dbpath = textBox1.Text + ".bak";//注意后缀名以 '.bak' 结尾
SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
oSQLServer.LoginSecure = true;
oSQLServer.Connect("(local)", "sa", "");
oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
oBackup.Database = dbname; oBackup.Files = dbpath;
oBackup.BackupSetName = dbpath;
oBackup.BackupSetDescription = "数据库备份";
oBackup.Initialize = true;
oBackup.SQLBackup(oSQLServer);
MessageBox.Show("备份成功!");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
//throw (new Exception("恢复数据库失败,请关闭所有和该数据库连接的程序!" + err.Message));
}
finally
{
oSQLServer.DisConnect();
}
}
//************************** //选择恢复位置
private void button4_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
textBox3.Text = openFileDialog1.FileName;
}
// 恢复备份的数据库
private void button2_Click(object sender, EventArgs e)
{ string dbname = textBox4.Text;
string dbpath = textBox3.Text;
SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
oSQLServer.LoginSecure = false;
oSQLServer.Connect("(local)", "sa", "");
//取得所有的进程列表:
SQLDMO.QueryResults qr = oSQLServer.EnumProcesses(-1);
//找到和要恢复数据库相关的进程并杀死:
int iColPIDNum = -1; int iColDbName = -1;
//循环进程列表
for (int i = 1; i <= qr.Columns; i++)
{
//获取名称
string strName = qr.get_ColumnName(i);
//如果等于进程id
if (strName.ToUpper().Trim() == "SPID")
{
iColPIDNum = i;
}
//如果等于dbname
else if (strName.ToUpper().Trim() == "DBNAME")
{ iColDbName = i; }
if (iColPIDNum != -1 && iColDbName != -1) break; }
//逐一把捕捉到的进程关闭
for (int i = 1; i <= qr.Rows; i++)
{
int lPID = qr.GetColumnLong(i, iColPIDNum);
string strDBName = qr.GetColumnString(i, iColDbName);
if (strDBName.ToUpper() == dbname.ToUpper())
{
oSQLServer.KillProcess(lPID);
}
}
oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
oRestore.Database = dbname;
oRestore.Files = dbpath; oRestore.FileNumber = 1;
oRestore.ReplaceDatabase = true;
oRestore.SQLRestore(oSQLServer);
MessageBox.Show("恢复数据库成功!");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
//throw (new Exception("恢复数据库失败,请关闭所有和该数据库连接的程序!" + err.Message));
}
finally { oSQLServer.DisConnect(); }
}
}
}