asp.net 版本一鍵升級,後臺直接調用升級腳本

應客戶需求,要求實現一個版本一鍵升級的功能,諮詢過同事以後弄了個demo出來,後臺代碼以下:sql

  //DBConnModelInfo:鏈接字符串的對象 (包含數據庫實例名,數據庫名,登錄名,登錄密碼)數據庫

  public bool DBVersionSaveData(DBConnModelInfo mdl)
        {
            bool result = false;

            try
            {
                int timeout = 60000; //設置執行超時時間,單位毫秒
                string prversion = WebConfig.Version;//程序版本
                string dbversion = new BSystemParameter().GetDBVersion();//數據庫版本
                
                //升級腳本的物理路徑
                string root = "DataBase\\Update";
                string folder = prversion;
                string rootpath = Path.Combine(root, folder);
                string dirpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootpath);

                string filepath = Path.Combine(dirpath, "Update.sql");//升級腳本
                string logpath = Path.Combine(dirpath, "Update.txt");//存放執行結果
                string destfilename = string.Format("Update_{0}.sql", mdl.InitialCatalog);//要執行升級的腳本(升級腳本的副本,不改變原升級腳本)
                string destfilepath = Path.Combine(dirpath, destfilename);


                if (System.IO.File.Exists(destfilepath))
                {
                    Tools.DeleteFile(@destfilepath);//刪除文件
                }
                //將升級腳本的內容複製到副本
                if (!System.IO.File.Exists(destfilepath))
                {
                    using (StreamWriter sw = new StreamWriter(destfilepath, true, Encoding.Unicode))
                    {
                        sw.WriteLine(string.Format("Use [{0}]", mdl.InitialCatalog));//mdl.InitialCatalog 數據庫名
                        sw.WriteLine("Go");

                        string[] rals = System.IO.File.ReadAllLines(@filepath);
                        foreach (string s in rals)
                        {
                            sw.WriteLine(s);
                        }
                    }
                }
                //執行升級腳本
                if (System.IO.File.Exists(destfilepath))
                {
                    Process p = new Process();
                    p.StartInfo.FileName = "osql.exe"; //執行腳本的方式
                    /* -S:數據庫實例名  -U:登陸名 -P:密碼 -i:升級的腳本路徑 -o:執行後結果存放路徑  */
                    string args = string.Format(@"-S {0}  -U {1} -P {2} -i ""{3}"" -o ""{4}""", mdl.DataSource, mdl.UserID, mdl.Password, destfilepath, logpath);
                    p.StartInfo.Arguments = args;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.CreateNoWindow = true;
                    p.Start();
                    p.WaitForExit(timeout);
                    p.Close();

                    result = true;
                }                
            }
            catch (Exception ex)
            {
                Tools.Log(this.GetType().Name, new StackFrame(1).GetMethod().Name, ex);//錯誤日誌
                result = false;
            }
            
            return result;
        }this

相關文章
相關標籤/搜索