C#执行.sql文件中命令

首先是一个不需要修改的方法,拿来就用

        private string ExeCommand(string commandText)
        {

            System.Diagnostics.Process p = new System.Diagnostics.Process();

            p.StartInfo.FileName = "cmd.exe";

            p.StartInfo.UseShellExecute = false;

            p.StartInfo.RedirectStandardInput = true;

            p.StartInfo.RedirectStandardOutput = true;

            p.StartInfo.RedirectStandardError = true;

            p.StartInfo.CreateNoWindow = true;

            string strOutput = null;

            try
            {

                p.Start();

                p.StandardInput.WriteLine(commandText);

                p.StandardInput.WriteLine("exit");

                strOutput = p.StandardOutput.ReadToEnd();

                p.WaitForExit();

                p.Close();

            }

            catch (Exception e)
            {

                strOutput = e.Message;

            }

            return strOutput;

        }  

其调用方法就两句话

string sqlQuery = "osql.exe   -U" + loginName + "   -P" + loginPwd + "   -S" + serverIp + "   -d" + dbName + "   -iyoursql.sql";

string strRst = ExeCommand(sqlQuery);

posted @ 2010-02-02 12:50    阅读(256)  评论(0编辑  收藏  举报