SQL Server 2008 Express连接字符串引发实例失败异常

时间:2015-07-07 23:05:12

标签: c# sql-server-2008 connection-string

我使用以下代码打开与SQL Server 2008 Express实例的数据库连接,并从数据库脚本运行查询

private void ExecuteSql(String serverName, String sql)
{
    String connectionString = String.Format("Server={0};Initial Catalog=master;Integrated Security=True;MultipleActiveResultSets=True;User Instance=False;Context Connection=False;Connect Timeout=300;", serverName.Trim());
    MessageBox.Show(connectionString);

    SqlConnection sqlConnection = new SqlConnection(connectionString);
    SqlCommand command = new SqlCommand();
    command.Connection = sqlConnection;
    sqlConnection.Open();

    try
    {
        var scripts = Regex.Split(sql, @"^\s*GO\s* ($ | \-\- .*$)", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);

        foreach (var splitScript in scripts.Where(x => !String.IsNullOrWhiteSpace(x)).Select(x => x.Trim(' ', '\r', '\n')))
        {
            MessageBox.Show(splitScript);
            command.CommandText = splitScript;
            command.ExecuteNonQuery();
        }
    }
    finally
    {
        sqlConnection.Close();
    }
}

当我运行代码时,我总是收到异常消息"实例失败"

如果我换行

String connectionString = String.Format("Server={0};Initial Catalog=master;Integrated Security=True;MultipleActiveResultSets=True;User Instance=False;Context Connection=False;Connect Timeout=300;", serverName.Trim());

由同一行但硬编码服务器名称参数

String connectionString = "Server=MACHINE-NAME\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;MultipleActiveResultSets=True;User Instance=False;Context Connection=False;Connect Timeout=300;";

一切正常。

我尝试了很多不同的方法来创建连接字符串(String.formatSqlConnectionStringBuilder,字符串连接...)但到目前为止,所有这些方法在使用{时都会引发同样的问题{1}}参数而不是硬编码

0 个答案:

没有答案