无法使用smo从c#执行脚本

Rag*_*bar 2 c# sql-server asp.net winforms

我开发了一个C#Windows应用程序,我需要在客户端计算机上创建一个数据库,我已经在客户端计算机上创建了一个脚本文件并安装了SQL Server 2008 R2.

但是当我从我的代码执行脚本时,它总是显示错误:

无法连接数据库.

我添加了引用的SMO程序集

C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll 
Run Code Online (Sandbox Code Playgroud)

我的代码是:

string sqlConString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=mydatabase;Data Source=(local)";
FileInfo file = new FileInfo(dbPath);

string script = file.OpenText().ReadToEnd();

SqlConnection con = new SqlConnection(sqlConString);

Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);

file.OpenText().Close();
Run Code Online (Sandbox Code Playgroud)

Mik*_*oud 5

这样的事情怎么样:

using (SqlConnection cnn = new SqlConnection(sqlConString))
{
    var cmds = File.ReadAllText(@"path\to\file").Split(new string[] { "GO" },
        StringSplitOptions.RemoveEmptyEntries);

    cnn.Open();
    foreach (var cmd in cmds)
    {
        using (SqlCommand cmd = new SqlCommand(cmd, cnn))
        {
            cmd.ExecuteNonQuery();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用这种方法,您可以获得所需的内容,脚本可以执行,但您不必使用缓慢而臃肿的SMO界面.此外,您正在利用该using语句,因此您不必担心未管理的资源被打开.

现在,为了解决这个问题failed to connect to database...,我在第一次看到它时明显错过了,如果发生这种情况意味着:

Initial Catalog=mydatabase;Data Source=(local)
Run Code Online (Sandbox Code Playgroud)

有可能不正确.如果是,您的服务器可能不接受Windows身份验证.

我不知道你的本地机器的设置,但很可能是服务器(local)\SQLEXPRESS.