How to execute an .SQL script file using c#

后端 未结 10 801
忘了有多久
忘了有多久 2020-11-22 17:03

I\'m sure this question has been answered already, however I was unable to find an answer using the search tool.

Using c# I\'d like to run a .sql file. The sql file

10条回答
  •  隐瞒了意图╮
    2020-11-22 17:53

    Using EntityFramework, you can go with a solution like this. I use this code to initialize e2e tests. De prevent sql injection attacks, make sure not to generate this script based on user input or use command parameters for this (see overload of ExecuteSqlCommand that accepts parameters).

    public static void ExecuteSqlScript(string sqlScript)
    {
        using (MyEntities dataModel = new MyEntities())
        {
            // split script on GO commands
            IEnumerable commands = 
                Regex.Split(
                    sqlScript, 
                    @"^\s*GO\s*$",
                    RegexOptions.Multiline | RegexOptions.IgnoreCase);
    
            foreach (string command in commands)
            {
                if (command.Trim() != string.Empty)
                {
                    dataModel.Database.ExecuteSqlCommand(command);
                }
            }              
        }
    }
    

提交回复
热议问题