Connect to SQL with AppConfig

0

How can I make a connection to SQL with the connectionstring in AppConfig?

I did this, but I wish it could be by AppConfig, how can I do it?

private void button1_Click(object sender, EventArgs e)
    {
        string connectionString = @"Data Source=SQL;Initial Catalog=Banco;Persist Security Info=True;User ID=sa;Password=Senha";
        SqlConnection con = new SqlConnection(connectionString);
        try
        {
            con.Open();
            MessageBox.Show("Conectado com sucesso");
        }
        catch
        {
            MessageBox.Show("Erro ao conectar");
        }
    }
    
asked by anonymous 21.09.2017 / 16:24

2 answers

1

On your app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="MinhaConnString" connectionString="Data Source=SQL;Initial Catalog=Banco;Persist Security Info=True;User ID=sa;Password=Senha" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

You can get the connection string like this:

string connectionStr = 
System.Configuration.ConfigurationManager.
ConnectionStrings["MinhaConnString"].ConnectionString;

SqlConnection con = new SqlConnection(connectionStr);
// ...

You need to reference assembly System.Configuration.dll

    
21.09.2017 / 16:28
0

In your app.config place:

<connectionStrings>
    <add name="myConnectionString" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

And then you can create the connection this way:

SqlConnection con = new SqlConnection(
    WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
    
21.09.2017 / 16:31