C# 執行sql腳本


        /// <summary>
        /// 使用sqlcmd執行sql腳本
        /// </summary>
        /// <param name="strSqlscripFile">腳本文件存放位置</param>
        void ExecuteSqlScript(string strSqlscripFile)
        {
//拼接文件路徑,在路徑手尾添加“”,避免路徑包含空格造成文件讀取失敗 string fileName = @"""" + strSqlscripFile + @"""";
//拼接命令行 例如"sqlcmd -S (local) -i D:\DHGateAssistant.sql" string arguments = String.Format(@"sqlcmd -S {0} -i {1}", @"(local)", fileName); // 調用sqlcmd ProcessStartInfo info = new ProcessStartInfo("cmd.exe", arguments); //設定參數,其中的“/C”表示執行完命令後馬上退出 info.Arguments = "/C " + arguments; //禁用OS Shell info.UseShellExecute = false; //禁止彈出新窗口 info.CreateNoWindow = true; //隱藏windows style info.WindowStyle = ProcessWindowStyle.Hidden; //標準輸出 info.RedirectStandardOutput = true; Process proc = new Process(); proc.StartInfo = info; try { //啓動進程 proc.Start(); //等待程序執行.Sql腳本 proc.WaitForExit(); proc.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (proc != null) proc.Close(); } }


 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章