參考資料來源:
https://www.youtube.com/watch?v=-fl7PQ7vpCY&ab_channel=CsharpTutorials
https://csharp-tutorials1.blogspot.com/2016/03/backup-and-restore-sql-server-database.html
函式庫:
using System;
using System.Windows;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
聲明數據庫的connectionString:
SqlConnection con = new SqlConnection(Final_window.Properties.Settings.Default.Final_windowConnectionString);
備份:
選擇備份路徑(備份到哪一個文件夾中)
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.SelectedPath;
BackupButton.Enabled = true;
}
}
備份並輸出
private void BackupButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
try
{
if(textBox1.Text==string.Empty)
{
MessageBox.Show("please enter backup file location");
}
else
{
string cmd = "BACKUP DATABASE [" + database + "] TO DISK='" + textBox1.Text + "\\" + "database" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";
using(SqlCommand command = new SqlCommand(cmd,con))
{
if(con.State!=ConnectionState.Open)
{
con.Open();
}
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("database backup done successefully");
BackupButton.Enabled = false;
}
}
}
catch
{
}
}
復原:
選擇路徑,選擇所要恢復的資料庫bak檔案
private void Browsebutton2_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "SQL SERVER database backup files|*.bak";
dlg.Title = "Database restore";
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox2.Text = dlg.FileName;
restoreButton.Enabled = true;
}
}
復原資料庫
private void restoreButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
string sqlStmt2 = string.Format("ALTER DATABASE [" + database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE DATABASE [" + database + "] FROM DISK='" + textBox2.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER DATABASE [" + database + "] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("database restoration done successefully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}