小编典典

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

c#

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

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


阅读 948

收藏
2020-05-19

共1个答案

小编典典

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);
    }
}
2020-05-19