What is the best way to handle multiple database connections in C#

拜拜、爱过 提交于 2019-12-05 12:36:44

Instead of adding variables, why not make a class?

public class MyDatabaseConnection {
    public MyDatabaseConnection(string connectionString) {
        this.connectionString = connectionString;
        // create a database connection perhaps
    }
    // some methods for querying a database
    public void execute(string query) { }
}

In this case it's easy to add a third database connection

MyDatabaseConnection con1 = new MyDatabaseConnection("Server=localhost");
MyDatabaseConnection con2 = new MyDatabaseConnection("Server=other_server");
MyDatabaseConnection con3 = new MyDatabaseConnection("Server=third_one");

And execute an sql query on each

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

If you're going to be doing low-level database access, this seems fine to me. Of course, if you only need one database connection open at any time, you could abstract most of the code into a method (that takes an SQL command/text as a parameter and returns the result), but this may not be the case in your situation.

You could also make things slightly neater by making use of using statements, as such:

using(var sqlConnectionA = new ...)
using(var sqlConnectionB = new ...)
{
    try
    {
        // Perform queries here.
    }
    catch (SqlException exSql)
    {
        // SQL error
    }
}

If you need all two (or three, or...) connetions open at the same time and need to retain the SqlCommand for each of them, then yes, you're probably going to have to do it the way you're doing it.

However, if you only need one connection open at a time, you could use a single connection and single command, then change things as needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!