How to execute an .SQL script file using c#

后端 未结 10 804
忘了有多久
忘了有多久 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条回答
  • There are two points to considerate.

    1) This source code worked for me:

    private static string Execute(string credentials, string scriptDir, string scriptFilename)
    { 
      Process process = new Process();
      process.StartInfo.UseShellExecute = false;
      process.StartInfo.WorkingDirectory = scriptDir;
      process.StartInfo.RedirectStandardOutput = true;
      process.StartInfo.FileName = "sqlplus";
      process.StartInfo.Arguments = string.Format("{0} @{1}", credentials, scriptFilename);
      process.StartInfo.CreateNoWindow = true;
    
      process.Start();
      string output = process.StandardOutput.ReadToEnd();
      process.WaitForExit();
    
      return output;
    }
    

    I set the working directory to the script directory, so that sub scripts within the script also work.

    Call it e.g. as Execute("usr/pwd@service", "c:\myscripts", "script.sql")

    2) You have to finalize your SQL script with the statement EXIT;

    0 讨论(0)
  • 2020-11-22 17:52

    Put the command to execute the sql script into a batch file then run the below code

    string batchFileName = @"c:\batosql.bat";
    string sqlFileName = @"c:\MySqlScripts.sql";
    Process proc = new Process();
    proc.StartInfo.FileName = batchFileName;
    proc.StartInfo.Arguments = sqlFileName;
    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    proc.StartInfo.ErrorDialog = false;
    proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileName);
    proc.Start();
    proc.WaitForExit();
    if ( proc.ExitCode!= 0 )
    

    in the batch file write something like this (sample for sql server)

    osql -E -i %1
    
    0 讨论(0)
  • 2020-11-22 17:53
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.SqlServer.Management.Smo;
    using Microsoft.SqlServer.Management.Common;
    using System.IO;
    using System.Data.SqlClient;
    
    public partial class ExcuteScript : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string sqlConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ccwebgrity;Data Source=SURAJIT\SQLEXPRESS";
    
            string script = File.ReadAllText(@"E:\Project Docs\MX462-PD\MX756_ModMappings1.sql");
    
            SqlConnection conn = new SqlConnection(sqlConnectionString);
    
            Server server = new Server(new ServerConnection(conn));
    
            server.ConnectionContext.ExecuteNonQuery(script);
        }
    }
    
    0 讨论(0)
  • 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<string> 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);
                }
            }              
        }
    }
    
    0 讨论(0)
提交回复
热议问题