简体   繁体   English

将ConnectionString移至App.config

[英]Move ConnectionString to App.config

In my WPF-Application I want to connect to a database. 在我的WPF应用程序中,我想连接到数据库。

If I use the following code it just works fine: 如果我使用以下代码,则可以正常工作:

string connectionString = @"Data Source=SERVER\ENGINE;Initial Catalog=MyDb;User ID=sa;Password=123456;";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

Now I moved the ConnectionString to my App.config and want to use from there with the following code: 现在,我将ConnectionString移到我的App.config并希望在其中使用以下代码:

string connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

Now I get an SqlExecption : 现在我得到一个SqlExecption

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll System.Data.dll中发生了类型为'System.Data.SqlClient.SqlException'的未处理的异常

A network-related or instance-specific error occurred while establishing a connection to SQL Server. 建立与SQL Server的连接时发生与网络相关或特定于实例的错误。 The server was not found or was not accessible. 服务器未找到或无法访问。 Verify that the instance name is correct and that SQL Server is configured to allow remote connections. 验证实例名称正确,并且已将SQL Server配置为允许远程连接。 (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (提供者:SQL网络接口,错误:26-指定服务器/实例时出错)

The App.config looks like: App.config看起来像:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <connectionStrings >
    <add connectionString="Data Source=SERVER\ENGINE;Initial Catalog=MyDb;User ID=sa;Password=123456;" name="connection"/>
  </connectionStrings>
</configuration>

Why does this not work? 为什么这不起作用?

Try this:- (Prefer Names instead of index) 尝试以下操作:-(首选名称而不是索引)

ConfigurationManager.ConnectionStrings["connection"].ConnectionString;

You can read why we should Here . 您可以在这里阅读为什么要这么做

You can always get the connection string by its name parameter: 您始终可以通过其name参数获取连接字符串:

ConfigurationManager.ConnectionStrings["connection"].ConnectionString;

Source: http://msdn.microsoft.com/pt-br/library/ms178411(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1 来源: http : //msdn.microsoft.com/pt-br/library/ms178411(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM