C# 批量执行sql脚本

  public void GetFilePath()
        {
            string ConfigPath = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(ConfigPath);
            XmlNode root = xmlDoc.SelectSingleNode("configuration");

            //解析connectionStringItems
            XmlNode list = root.SelectSingleNode("connectionStringItems");
            //循环遍历数据库连接Items
            foreach (XmlNode item in list.ChildNodes)
            {
                string ConnStr = item.InnerText;

                //获取数据库字符串中所有信息
                SqlConnection conn = new SqlConnection(ConnStr);
                SqlConnectionStringBuilder sqlSb = new SqlConnectionStringBuilder(ConnStr);
                string userId = sqlSb.UserID;  //获取登录名
                string password = sqlSb.Password; //获取数据库密码
                string ServerIP = conn.DataSource; //获取数据库连接IP
                string DataBase = conn.Database; //获取数据库名字           

                var files = Directory.GetFiles(FilePath, "*.sql");
                foreach (var it in files)
                {
                    string sqlQuery = "sqlcmd.exe -U  " + userId + "  -P " + password + " -S " + ServerIP + " -d " + DataBase + " -i " + it + " ";
                    string result = ExeCommand(sqlQuery);
                }
            }
        }
        /// 
        /// 执行sql语句方法
        /// 
        /// SQL语句
        /// 
        public static string ExeCommand(string commandText)
        {
            Process p = new 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;
        }

 

 

你可能感兴趣的:(WinFom,c#)