How to have the option to connect to more than one database in my C # Visual Studio application by app.config

0

I have a C # application that I did in Visual Studio. This application connects to a Sql Server database. I would like to put in my login a list option to choose another bank if I have more than one in my application. For example: a ctrl + c ctrl + v from the same bank but two different companies. I am using the app.config with the string similar to this

<connectionStrings>
  <add name="MinhaStringDeConexao"
       connectionString="Data Source=(local); Initial Catalog=MinhaDb; Integrated Security=SSPI;"
       providerName="SqlClient"/>
</connectionStrings>

How do I put more connections in there and how do I retrieve them in my main form after login. Thanks in advance for your help.

    
asked by anonymous 30.05.2018 / 16:08

1 answer

0

Instead of adding variables, I strongly advise you to create a class! More practical and takes less space.

like this:

public class MyDatabaseConnection {
    public MyDatabaseConnection(string connectionString) {
        this.connectionString = connectionString;
        // criar uma conexa à bd
    }
    // alguns metodos para fazer a query á BD
    public void execute(string query) { }
}

This makes it easier to add 1,2,3 or more connections

MyDatabaseConnection con1 = new MyDatabaseConnection("Server=etc_etc_bd");
MyDatabaseConnection con2 = new MyDatabaseConnection("Server=dois_bd");
MyDatabaseConnection con3 = new MyDatabaseConnection("Server=um_bd");

And execute Query on each one (QUERY = QUESTION)

MyDatabaseConnection[] cons = new MyDatabaseConnection[]{ con1, con2, con3 };
foreach (MyDatabaseConnection con in cons) {
    con.execute(someSqlCommandText);
}
    
30.05.2018 / 16:23