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

Asked

Viewed 51 times

0

I have a C# application I made in Visual Studio. This application connects to an Sql Server database. I would like to put on my login an option in list form 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 from two different companies. I’m using the app.config with the string similar to this one

<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 recover them in my main form after login. Thanks for the help.

  • only put another line inside connectionStrings Uai, then access each connection by attribute name

1 answer

0


Instead of adding variables, I seriously advise you to create a class! More convenient and takes up less space.

thus:

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, be it 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 the Query in each one (QUERY = QUESTION)

MyDatabaseConnection[] cons = new MyDatabaseConnection[]{ con1, con2, con3 };
foreach (MyDatabaseConnection con in cons) {
    con.execute(someSqlCommandText);
}
  • I’m not very experienced in C# yet, where do I create this class? In the main form? how do I call it in other forms?

Browser other questions tagged

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