如何使用C#执行一个.SQL脚本文件

19 浏览
0 Comments

如何使用C#执行一个.SQL脚本文件

我相信这个问题已经有答案了,但是我在使用搜索工具时未能找到答案。

我想在c#中运行一个.sql文件。.sql文件包含多个sql语句,其中有一些跨越多行。我尝试读取文件并尝试使用ODP.NET执行文件...但我认为ExecuteNonQuery不是真正设计做这件事的。

所以我尝试使用sqlplus通过生成进程...但是,除非我在UseShellExecute设置为true时生成进程,否则sqlplus会挂起并且永远不会退出。这是不起作用的代码。

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的一个副作用是您无法捕获重定向的输出。

admin 更改状态以发布 2023年5月23日
0
0 Comments

我尝试使用 Microsoft.SqlServer.Management 解决方案,但在 .NET 4.0 下表现不佳,所以我又写了另一个只使用 .NET libs 框架的解决方案。

string script = File.ReadAllText(@"E:\someSqlScript.sql");
// split script on GO command
IEnumerable 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();

0
0 Comments
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);
    }
}

意为在html中添加一个加粗的标签,文本内容为“123”。

0