如何使用 c# 执行 .SQL 脚本文件 [英] How to execute an .SQL script file using c#

查看:39
本文介绍了如何使用 c# 执行 .SQL 脚本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm sure this question has been answered already, however I was unable to find an answer using the search tool.

使用 c# 我想运行一个 .sql 文件.sql 文件包含多个 sql 语句,其中一些语句被分成多行.我尝试读入文件并尝试使用 ODP.NET 执行文件......但是我认为 ExecuteNonQuery 并不是真正设计用于执行此操作.

Using c# I'd like to run a .sql file. The sql file contains multiple sql statements, some of which are broken over multiple lines. I tried reading in the file and tried executing the file using ODP.NET ... however I don't think ExecuteNonQuery is really designed to do this.

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

So I tried using sqlplus via spawning a process ... however unless I spawned the process with UseShellExecute set to true sqlplus would hang and never exit. Here's the code that DOESN'T WORK.

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

WaitForExit never returns .... Unless I set UseShellExecute to true. A side effect of UseShellExecute is that you can no capture the redirected output.

推荐答案

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=SURAJITSQLEXPRESS";

        string script = File.ReadAllText(@"E:Project DocsMX462-PDMX756_ModMappings1.sql");

        SqlConnection conn = new SqlConnection(sqlConnectionString);

        Server server = new Server(new ServerConnection(conn));

        server.ConnectionContext.ExecuteNonQuery(script);
    }
}

这篇关于如何使用 c# 执行 .SQL 脚本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆