备份数据库:
string connectionString = "server=服务器名称;database=数据库名;uid=登入名;pwd=登入密码"; //登入名和密码在SQL Server中查找
private void btnBackDataBase_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog sf = new SaveFileDialog();
DialogResult dr = sf.ShowDialog();
if (dr == DialogResult.OK)
{
string path = sf.FileName;
string sql = " BACKUP DATABASE 数据库名 to DISK = '" + path + "'";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
MessageBox.Show("数据库备份成功");
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
数据库还原:
private void btnRestore_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
try
{
string cmdText = @"restore database 数据库名 from disk='" + ofd.FileName + "'";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string setOffline = "Alter database 数据库名 Set Offline With rollback immediate ";
string setOnline = " Alter database 数据库名 Set Online With Rollback immediate";
string sql = setOffline + cmdText + setOnline;
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}