日期:2014-05-18  浏览次数:20865 次

求SQL备份与恢复的源代码!!!!!!c#
求SQL备份与恢复的源代码
用c#

------解决方案--------------------
以下内容供你参考
http://www.csharphelp.com/archives2/archive345.html
http://dev.csdn.net/article/28/28564.shtm
------解决方案--------------------
private void BackUpSQLServer()
{
string str = strPath + "\\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
string strConnectstring = "Server=" + this.textBox2.Text.Trim() + ";Database=Master;User ID=" + this.textBox4.Text.Trim() + ";Password=" + textBox4.Text.Trim() + ";";
SqlConnection conn = new SqlConnection(strConnectstring);

SqlCommand cmdBK = new SqlCommand();
cmdBK.CommandType = CommandType.Text;
cmdBK.Connection = conn;
cmdBK.CommandText = @"backup database " + textBox3.Text.Trim() + " to disk='" + str + "' with init";

try
{
conn.Open();
cmdBK.ExecuteNonQuery();
this.richTextBox1.Text = "备份成功\n文件路径为:" + str + "\n操作时间:\n" + DateTime.Now.ToString();

this.richTextBox1.ForeColor = Color.Blue;
}
catch (Exception ex)
{
this.richTextBox1.Text = "备份失败\n失败原因\n" + ex.ToString() + "\n操作时间\n" + DateTime.Now.ToString();
this.richTextBox1.ForeColor = Color.Red;
}
finally
{
conn.Close();
conn.Dispose();
}
}

private void RestoreSQLServer()
{
string strConnectstring = "Server=" + this.textBox2.Text.Trim() + ";Database=Master;User ID=" + this.textBox4.Text.Trim() + ";Password=" + textBox5.Text.Trim() + ";";
SqlConnection conn = new SqlConnection(strConnectstring);
conn.Open();

//KILL DataBase Process 
SqlCommand cmd = new SqlCommand("SELECT spid FROM dbo.sysprocesses ,dbo.sysdatabases WHERE dbo.sysprocesses.dbid=dbo.sysdatabases.dbid AND dbo.sysdatabases.Name='" + textBox3.Text.Trim() + "'", conn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
cmd.ExecuteNonQuery();
}

SqlCommand cmdRT = new SqlCommand();
cmdRT.CommandType = CommandType.Text;
cmdRT.Connection = conn;
cmdRT.CommandText = @"restore database " + textBox3.Text.Trim() + " from disk='" + strPath + "'";

try
{
cmdRT.ExecuteNonQuery();
this.richTextBox1.Text = "还原成功\n文件路径为:" + strPath + "\n操作时间:\n" + DateTime.Now.ToString();
this.richTextBox1.ForeColor = Color.Blue;
}
catch (Exception ex)
{
this.richTextBox1.Text = "还原失败\n失败原因\n" + ex.ToString() + "\n操作时间:\n" + DateTime.Now.ToString();
this.richTextBox1.ForeColor = Color.Red;
}
finally
{
conn.Close();