0
我在寫一個Windows Forms應用程序來備份我的SQL Server數據庫。我正在使用以下代碼:在C#中自動執行SQL Server備份#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SQL_Server_DB_Backup_and_Restore
{
public partial class Form1 : Form
{
private SqlConnection conn;
private SqlCommand command;
private SqlDataReader reader;
string sql = "";
string connectionString = "";
public Form1()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if(dlg.ShowDialog()==DialogResult.OK)
{
txtBackupFileLocation.Text = dlg.SelectedPath;
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
connectionString = "Data Source= " + txtDataSource.Text + "; User Id=" + txtUserId.Text + "; Password=" + txtPassword.Text + "";
conn = new SqlConnection(connectionString);
conn.Open();
//sql = "EXEC sp_databases";
sql = "SELECT * FROM sys.databases d WHERE d.database_id>4";
command = new SqlCommand(sql, conn);
reader = command.ExecuteReader();
cmbDatabases.Items.Clear();
while(reader.Read())
{
cmbDatabases.Items.Add(reader[0].ToString());
}
txtDataSource.Enabled = false;
txtUserId.Enabled = false;
txtPassword.Enabled = false;
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
btnBackup.Enabled = true;
btnRestore.Enabled = true;
cmbDatabases.Enabled = true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
txtDataSource.Enabled = true;
txtUserId.Enabled = true;
txtPassword.Enabled = true;
cmbDatabases.Enabled = false;
btnBackup.Enabled = false;
btnRestore.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
btnDisconnect.Enabled = false;
cmbDatabases.Enabled = false;
btnBackup.Enabled = false;
btnRestore.Enabled = false;
}
private void btnBackup_Click(object sender, EventArgs e)
{
try
{
if(cmbDatabases.Text.CompareTo("")==0)
{
MessageBox.Show("Please select a database");
return;
}
conn = new SqlConnection(connectionString);
conn.Open();
sql = "BACKUP DATABASE " + cmbDatabases.Text + " TO DISK = '" + txtBackupFileLocation.Text + "\\" + cmbDatabases.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";
command = new SqlCommand(sql, conn);
command.ExecuteNonQuery();
MessageBox.Show("Database backup is completed successfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
現在我必須按一個按鈕才能進行備份。我該如何自動化該過程,以便我的應用程序可以每週進行一次備份?
Windows調度程序可以運行你的程序,當你想運行。只需選擇您的exe文件並安排運行時間。在這種情況下,你不需要一個表單應用程序。控制檯應用程序會這樣做。在Main Method中調用您的方法。 – Badiparmagi
以編程方式添加計劃任務的這個問題可能會有用。 http://stackoverflow.com/questions/7394806/creating-scheduled-tasks – scotru