窗体有一个textbox 和 SaveFileDialog
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WinUpload
{
public partial class BackUpDB : Form
{
public BackUpDB()
{
InitializeComponent();
}
private void BackUpDB_Load(object sender, EventArgs e)
{
}
button3_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("备份名不能为空!", "提示");
}
else
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "备份文件(*.bak)|*.bak";
sfd.FileName = textBox1.Text;
if (sfd.ShowDialog() == DialogResult.OK)
{
textBox2.Text = sfd.FileName;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox2.Text == "")
{
MessageBox.Show("位置不能为空!","提示");
}
else
{
SQLDMO.Backup oBackUp = new SQLDMO.BackupClass();
SQLDMO.SQLServer oSqlServer = new SQLDMO.SQLServerClass();
try
{
DataCenter dc = new DataCenter();
oSqlServer.LoginSecure = false;
oSqlServer.Connect("WEIJIA", "hu", "hu");
oBackUp.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
oBackUp.Database = dc.GetDataBaseName ;
oBackUp.Files = textBox2.Text.Trim();
oBackUp.BackupSetName = textBox1.Text.Trim();
oBackUp.BackupSetDescription = "数据库备份";
oBackUp.Initialize = true;
oBackUp.SQLBackup(oSqlServer);
MessageBox.Show("备份成功!","提示");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "失败");
}
finally
{
oSqlServer.DisConnect();
}
方法二: //DataCenter dc = new DataCenter();
//string path = @textBox2.Text.Trim(); ;
//string backupstr = "backup database wendang to disk='" + path + "';";
//SqlConnection con = new SqlConnection(dc.ConnectString);
//SqlCommand cmd = new SqlCommand(backupstr, con);
//try
//{
// con.Open();
// cmd.ExecuteNonQuery();
// MessageBox.Show("备份成功!");
// this.Close();
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.ToString(), "备份失败");
//}
//finally
//{
// con.Close();
//}
}
}
}