MS SQL database restore from dump

Материал из Помощь клиентам хостинга
Версия от 01:17, 12 января 2009; Admin (обсуждение | вклад) (Защищена страница «MS SQL database restore from dump» [edit=sysop:move=sysop])
Перейти к: навигация, поиск

Для того чтобы восстановить базу из дампа T-SQL типа (как его сделать описано в статье Делаем дамп базы MS SQL) используйте простой скрипт, листинг которо приведен ниже.

Предварительно выложите дамп на хостинге, в примере указана ссылка: http://windows.leaderhost.ru/user_qwerty.sql замените её на свой путь.

<geshi lang=asp source=SOURCE>

<%@ Page Language="C#" AutoEventWireup="true"  %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Net" %>


<%

    // полный Url до T-SQL дампа который надо восстановить
   string fileUrl = @"http://windows.leaderhost.ru/user_qwerty.sql";    
   
   // Connection string к серверу и базе для восстановления
   string connectionString = @"Server=mssql1.leaderhost.ru;Database=user_qwerty;uid=user_qwerty;pwd=123456";
   
   // Timeout of batches (in seconds)
   int timeout = 600;
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Executing T-SQL</title>

</head> <body>

   <form id="form1" runat="server">
   </form>
   <%
       SqlConnection conn = null;                   
       try
       {
           this.Response.Write(String.Format("Opening url {0}
", fileUrl)); // read file WebRequest request = WebRequest.Create(fileUrl); using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream())) { this.Response.Write("Connecting to SQL Server database...
"); // Create new connection to database conn = new SqlConnection(connectionString); conn.Open();
               while (!sr.EndOfStream)
               {
                   StringBuilder sb = new StringBuilder();
                   SqlCommand cmd = conn.CreateCommand();
                   
                   while (!sr.EndOfStream)
                   {
                       string s = sr.ReadLine();
                       if (s != null && s.ToUpper().Trim().Equals("GO"))
                       {
                           break;
                       }
                       
                       sb.AppendLine(s);
                   }
                   // Execute T-SQL against the target database
                   cmd.CommandText = sb.ToString();
                   cmd.CommandTimeout = timeout;
                   cmd.ExecuteNonQuery();
               }
           }
           this.Response.Write("T-SQL file executed successfully");
       }
       catch (Exception ex)
       {
           this.Response.Write(String.Format("An error occured: {0}", ex.ToString()));
       }
       finally
       {
           // Close out the connection
           //
           if (conn != null)
           {
               try
               {
                   conn.Close();
                   conn.Dispose();
               }
               catch (Exception e)
               {
                   this.Response.Write(String.Format(@"Could not close the connection.  Error was {0}", e.ToString()));
               }
           }
       }                       
               
       
        %>

</body> </html>

</geshi>