How to execute an .SQL script file using c#

后端 未结 10 808
忘了有多久
忘了有多久 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:47

    This works for me:

    public void updatedatabase()
    {
    
        SqlConnection conn = new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + txtdatabase.Text.Trim() + ";User ID=" + txtuserid.Text.Trim() + ";Password=" + txtpwd.Text.Trim() + "");
        try
        {
    
            conn.Open();
    
            string script = File.ReadAllText(Server.MapPath("~/Script/DatingDemo.sql"));
    
            // split script on GO command
            IEnumerable commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            foreach (string commandString in commandStrings)
            {
                if (commandString.Trim() != "")
                {
                    new SqlCommand(commandString, conn).ExecuteNonQuery();
                }
            }
            lblmsg.Text = "Database updated successfully.";
    
        }
        catch (SqlException er)
        {
            lblmsg.Text = er.Message;
            lblmsg.ForeColor = Color.Red;
        }
        finally
        {
            conn.Close();
        }
    }
    

提交回复
热议问题