App.config to access a SQL Server database?

1

How can I set this app.config to access my SQL Server database?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IServidor" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:2666/Servidor.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IServidor" contract="ServidorReference.IServidor"
                name="BasicHttpBinding_IServidor" />
        </client>
    </system.serviceModel>
</configuration>
    
asked by anonymous 15.12.2017 / 16:55

3 answers

0

To access your SQL Server , your app.config must have the connection strings

<connectionStrings>
  <add name="NomeDaStringDeConexao" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLExpress; Initial Catalog=SeuBanco;Integrated Security=True;MultipleActiveResultSets=True" />
</connectionStrings>
    
15.12.2017 / 16:57
0

Here is a complete example of app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>    
  <connectionStrings>
    <add name="SqlServerConnString" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=TestDB;Integrated Security=True;MultipleActiveResultSets=True" />
  </connectionStrings>
</configuration>

To return the string of the app.config use:

var connstring = ConfigurationManager.ConnectionStrings["SqlServerConnString"].ConnectionString;

This example I extracted from a GitHub mine repository, you can check it out as it is done.

link

    
17.12.2017 / 17:51
0

You can add a ConnectionString . Right after the startup tag in your App.config tag you can add:

    <connectionStrings>
        <add name="ConexaoSQLSERVER" 
             connectionString="Data Source=EnderecoServer; 
                               Initial Catalog=NomedaDB; 
                               Integrated Security=True;" 
             providerName="System.Data.SqlClient"/>
    </connectionStrings>

If you want to use a LocalDB and want to attack a database, your connectionString looks like this:

Server=.\SQLExpress;AttachDbFilename=C:\Caminho até a DB\MinhaDB.mdf;Database=NomedaDB;
Trusted_Connection=Yes;

To attack the DB in the project folder:

Server=.\SQLExpress;AttachDbFilename=|DiretoriodoProjeto|suadb.mdf;Database=NomedaDB;
Trusted_Connection=Yes;

Before starting to build the connection, make sure you do not forget to add the reference that the App.config handles.

In the project create a separate class to handle the connection:

AnexampleofusingConnectionDB:

    
17.12.2017 / 21:53