How to configure the Connection String in App.config?

1

I would like to mount using the saved string: InstanciaSQLServer , UserSQL and PWSQL , is it possible?

Example of my app.config

<configSections>


    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
        <-section name="BancoDeHoras.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
    </sectionGroup>
</configSections>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>    
<userSettings>
    <BancoDeHoras.Properties.Settings>
        <setting name="InstanciaSQLServer" serializeAs="String">
            <value />
        </setting>
        <setting name="UserSQL" serializeAs="String">
            <value />
        </setting>
        <setting name="PWSQL" serializeAs="String">
            <value />
        </setting>
    </BancoDeHoras.Properties.Settings>
</userSettings>
<connectionStrings>
  <add
    name="conection"
    connectionString ="Data Source =[InstanciaSQLServer]; Initial Catalog = BancoDeHoras; User id = [UserSQL]; pwd=[PWSQL]"/>
</connectionStrings>  

    
asked by anonymous 11.05.2017 / 13:28

2 answers

2

Your code

<connectionStrings>
  <add
    name="conection"
    connectionString ="Data Source =[InstanciaSQLServer]; Initial Catalog = BancoDeHoras; User id = [UserSQL]; pwd=[PWSQL]"/>
</connectionStrings>  

Example, let's say we have an instance of SQLEXPRESS that contains a database named TEST with user: sa, password: 123456

Your SQLEXPRESS instance matches your local or remote server.

It will look like this:

<connectionStrings>
  <add
    name="conection"
    connectionString ="Data Source =SQLEXPRESS ; Initial Catalog = TESTE; User id = SA; pwd=123456"/>
</connectionStrings> 

Your code is right, you just need to change the fields. A great site for you to check out the existing connection types link

    
11.05.2017 / 16:06
0

I solved the problem in a different way. I did not create the Connection String in XML app.Config , I created it directly in the class responsible for making the connection. That way my string looks like this:

private static string conexao_DB = $@"Data Source = {Properties.Settings.Default.InstanciaSQLSERVER}; 
Initial Catalog = BancoDeHoras; 
User id = {Properties.Settings.Default.UserSQL}; 
pwd={Properties.Settings.Default.PWSQL}"; 

I do not know if this is the right way to do it, but it was the only one I got so far.

    
11.05.2017 / 17:01