Connect to SQL with Appconfig

Asked

Viewed 41 times

0

How can I connect to SQL with connectionstring in Appconfig?

I did so, but I wish it could be for Appconfig, how can I do?

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");
        }
    }

2 answers

1


In his 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);
// ...

It is necessary to reference the Assembly System.Configuration.dll

  • I did this and my program closes when I click the button

  • This is the default code for this operation, confirm that the names are correct and the connection string as well. Throughout debug the code and see if it throws any error message.

  • Put the break-point and see and when the program closes

  • I’ve got it, thank you.

0

In your app.config put:

<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 that way:

SqlConnection con = new SqlConnection(
    WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.