ASP.NET 에서 코드 를 사용 하여 데이터 베 이 스 를 백업 하고 복원 합 니 다.

3641 단어 sqlc.netasp.netasp
--      
backup database db_CSManage to disk='c:\backup.bak'
--      ,                       
backup log db_CSManage to disk='c:\backup.bak'
restore database db_CSManage from disk='c:\backup.bak'

  그 중 dbCSManage 는 데이터베이스 이름 이 며,disk 뒤의 경 로 는 백업 파일 에 저 장 된 경로 입 니 다.SQL 문 구 를 알 게 되면.NET 코드 에서 훨씬 쉬 워 집 니 다.백업 한.NET 코드 는 다음 과 같 습 니 다.
try
{
	if (txtPath.Text != "" && txtName122.Text != "")
	{
		getSqlConnection geCon = new getSqlConnection();
		SqlConnection con = geCon.GetCon();

		string strBacl = "backup database db_CSManage to disk='" + txtPath.Text.Trim() + "\\" + txtName.Text.Trim() + ".bak'";
		SqlCommand Cmd = new SqlCommand(strBacl, con);
		if (Cmd.ExecuteNonQuery() != 0)
		{
			MessageBox.Show("      !", "   ", MessageBoxButtons.OK, MessageBoxIcon.Information);
			this.Close();
		}
		else
		{
			MessageBox.Show("      !", "   ", MessageBoxButtons.OK, MessageBoxIcon.Information);
		}

	}
	else
	{
		MessageBox.Show("              !", "   ", MessageBoxButtons.OK, MessageBoxIcon.Information);

	}// end 
}
catch (Exception ee)
{
	MessageBox.Show(ee.Message.ToString());
}

 다음은 데이터 베 이 스 를 복원 하 는 코드 입 니 다.예제 에서 처음에 이 데이터 베이스 와 관련 된 프로 세 스 를 삭제 한 다음 에 복원 하기 전에 데이터 베 이 스 를 시작 한 백업 파일 에 백업 한 다음 에 백업 파일 을 복원 해 야 합 니 다.그렇지 않 으 면 오류 가 발생 할 수 있 습 니 다.코드 는 다음 과 같 습 니 다.
if (textPaht.Text != "")
{
	getSqlConnection geCon = new getSqlConnection();
	SqlConnection con = geCon.GetCon();
	if (con.State == ConnectionState.Open)
	{
		con.Close();
	}
	string DateStr = "Data Source=niunan\\sqlexpress;Database=master;User id=sa;PWD=123456";
	SqlConnection conn = new SqlConnection(DateStr);
	conn.Open();

	//-------------------       db_CSManage       --------------
	string strSQL = "select spid from master..sysprocesses where dbid=db_id( 'db_CSManage') ";
	SqlDataAdapter Da = new SqlDataAdapter(strSQL, conn);

	DataTable spidTable = new DataTable();
	Da.Fill(spidTable);

	SqlCommand Cmd = new SqlCommand();
	Cmd.CommandType = CommandType.Text;
	Cmd.Connection = conn;

	for (int iRow = 0; iRow <= spidTable.Rows.Count - 1; iRow++)
	{
		Cmd.CommandText = "kill " + spidTable.Rows[iRow][0].ToString();   //         
		Cmd.ExecuteNonQuery();
	}
	conn.Close();
	conn.Dispose();
	//--------------------------------------------------------------------

	SqlConnection sqlcon = new SqlConnection(DateStr);
	sqlcon.Open();
	string sql = "backup log db_CSManage to disk='" + textPaht.Text.Trim() + "' restore database db_CSManage from disk='" + textPaht.Text.Trim() + "'";
	SqlCommand sqlCmd = new SqlCommand(sql, sqlcon);
	sqlCmd.ExecuteNonQuery();
	sqlCmd.Dispose();
	sqlcon.Close();
	sqlcon.Dispose();
	MessageBox.Show("      !", "  ", MessageBoxButtons.OK, MessageBoxIcon.Information);
	MessageBox.Show("        ,              。");
	Application.Exit();
}
else
{
	MessageBox.Show("       !", "  ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}

좋은 웹페이지 즐겨찾기