如何在c#中运行sql脚本

本文关键字:运行 sql 脚本 | 更新日期: 2023-09-27 18:16:59

我一直在寻找这个,我想我在这里找到了答案。这是我发现通过c#运行sql脚本的代码:

using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace SeleniumTest2
{
    class CreateSchema
    {
        public void Schema_Create()
        {
            string sqlConnectionString = "connection string here";
            FileInfo file = new FileInfo(@"filepath to script.sql");
            string script = file.OpenText().ReadToEnd();
            SqlConnection conn = new SqlConnection(sqlConnectionString);
            Server server = new Server(new ServerConnection(conn));
            //DOESNTLIKE
            server.ConnectionContext.ExecuteNonQuery(script);

            file.OpenText().Close();
            conn.Close();

        }
    }
}

但是我一直得到以下错误:

An unhandled exception of type 'Microsoft.SqlServer.Management.Common.ExecutionFailureException' occurred in Microsoft.SqlServer.ConnectionInfo.dll
Additional information: An exception occurred while executing a Transact-SQL statement or batch.
谁能告诉我如何克服这个错误?谢谢! !

如何在c#中运行sql脚本

这种情况在我身上发生过几次。调试后,我的脚本文件本身出现了一些错误。下面的方法对我有用:

  1. 尝试使用SQL Management Studio直接运行脚本文件。这可以查明脚本本身的错误。
  2. 将SQL脚本分解为更小的文件。出于某种原因,这对我很管用。相应地将文件拆分为更小的脚本。对于我的特定数据库创建脚本,我将其分为创建表脚本、填充表脚本和添加主键和外键脚本。
我的代码:
    /// <summary>
    /// Process SQL script with "GO" statements 
    /// </summary>
    /// <param name="script"></param>
    public static void ProcessSQLScriptFile(string script)
    {
        try
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.SQLConDefault); // your connection string 
            con.Open(); 
            Server server = new Server(new ServerConnection(con));
            server.ConnectionContext.ExecuteNonQuery(script);
            con.Close();
        }
        catch (SqlException e)
        {
            Console.WriteLine("SQL Exception: " + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }

希望这对你有帮助。

您可以尝试使用此方法执行sql (from msdn):

private static void ExecuteCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}

如果出现错误,请检查异常详细信息,检查连接字符串是否有效

我也有同样的问题。为我修复它的是找出实际的错误:

public void Schema_Create()
{
    string sqlConnectionString = "connection string here";
    FileInfo file = new FileInfo(@"filepath to script.sql");
    string script = file.OpenText().ReadToEnd();
    SqlConnection conn = new SqlConnection(sqlConnectionString);
    Server server = new Server(new ServerConnection(conn));
    try
    {
        server.ConnectionContext.ExecuteNonQuery(script);           
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: " + ex.InnerException.Message);
    }
    file.OpenText().Close();
    conn.Close();
}

我的问题出现在ex.InnerException.Message中,在我的情况下,我的脚本试图写一个已经存在于表上的列(列名必须是给定表的唯一)。

将数据库路径更改为另一个驱动器因为在c盘或windows盘中你没有权限创建数据库

如果改变路径,你的解决方案是工作成功。