首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用c#执行.SQL脚本文件

如何使用c#执行.SQL脚本文件
EN

Stack Overflow用户
提问于 2009-03-16 11:58:13
回答 8查看 311.9K关注 0票数 151

我确信这个问题已经得到了回答,但是我无法使用搜索工具找到答案。

使用c#,我想运行一个.sql文件。sql文件包含多个sql语句,其中一些语句被分成多行。我尝试读取文件,并尝试使用ODP.NET执行文件...然而,我并不认为ExecuteNonQuery真的是为此而设计的。

所以我试着通过派生一个进程来使用sqlplus ...但是,除非我在UseShellExecute设置为true的情况下生成进程,否则sqlplus将挂起并且永远不会退出。下面是不起作用的代码。

代码语言:javascript
复制
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "sqlplus";
p.StartInfo.Arguments = string.Format("xx/xx@{0} @{1}", in_database, s);
p.StartInfo.CreateNoWindow = true;

bool started = p.Start();
p.WaitForExit();

WaitForExit永远不会回来..。除非我将UseShellExecute设置为true。UseShellExecute的一个副作用是您无法捕获重定向的输出。

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2009-11-13 20:12:00

代码语言:javascript
复制
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);
    }
}
票数 205
EN

Stack Overflow用户

发布于 2011-10-12 21:48:31

我用Microsoft.SqlServer.Management尝试了这个解决方案,但它在.NET 4.0上不能很好地工作,所以我只用.NET libs框架写了另一个解决方案。

代码语言:javascript
复制
string script = File.ReadAllText(@"E:\someSqlScript.sql");

// split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);

Connection.Open();
foreach (string commandString in commandStrings)
{
    if (!string.IsNullOrWhiteSpace(commandString.Trim()))
    {
        using(var command = new SqlCommand(commandString, Connection))
        {
            command.ExecuteNonQuery();
        }
    }
}     
Connection.Close();
票数 116
EN

Stack Overflow用户

发布于 2017-08-09 23:42:26

这适用于Framework 4.0或更高版本。支持GO。还会显示错误消息、行和sql命令。

代码语言:javascript
复制
using System.Data.SqlClient;

        private bool runSqlScriptFile(string pathStoreProceduresFile, string connectionString)
    {
        try
        {
            string script = File.ReadAllText(pathStoreProceduresFile);

            // split script on GO command
            System.Collections.Generic.IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$",
                                     RegexOptions.Multiline | RegexOptions.IgnoreCase);
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                foreach (string commandString in commandStrings)
                {
                    if (commandString.Trim() != "")
                    {
                        using (var command = new SqlCommand(commandString, connection))
                        {
                        try
                        {
                            command.ExecuteNonQuery();
                        }
                        catch (SqlException ex)
                        {
                            string spError = commandString.Length > 100 ? commandString.Substring(0, 100) + " ...\n..." : commandString;
                            MessageBox.Show(string.Format("Please check the SqlServer script.\nFile: {0} \nLine: {1} \nError: {2} \nSQL Command: \n{3}", pathStoreProceduresFile, ex.LineNumber, ex.Message, spError), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return false;
                        }
                    }
                    }
                }
                connection.Close();
            }
        return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return false;
        }
    }
票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/650098

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档