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(); } }

 

 
posted @ 2013-06-06 11:56  参商  阅读(370)  评论(0)    收藏  举报