在 C# 中处理多个数据库连接的最佳方法是什么

What is the best way to handle multiple database connections in C#(在 C# 中处理多个数据库连接的最佳方法是什么)
本文介绍了在 C# 中处理多个数据库连接的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果说我需要针对两个单独的数据库运行两个单独的 SQL 语句.现在我做(伪代码):

If say I need to run two separate SQL statements against two separate databases. Right now I do (pseudocode):

Try{

declare variable connectionA to DatabaseA 
declare variable connectionB to DatabaseB 

connectionA.open()
connectionB.open() 


declare variable SQLCmdA with ConnectionA and one SQL statement 
declare variable SQLCmdB with ConnectionB and another SQL statement 

SQLCmdA.executeNonQuery() 
SQLCmdB.executeNonQuery()

}

Catch () 
{
   print error message
}

Finally(){ 
  connectionA.close() 
  connectionB.close()
  SQLCmdA.Dispose()
  SQLCmdB.Dispose() 
} 

上面看起来很笨拙.如果我有三个不同的 sql 语句,我将需要三个不同的 SQLCmd 变量.

The above seems very clumsy. And if I have three different sql statements, i would need three different SQLCmd variables.

是否有做这些事情的标准"方式,尤其是在效率、性能方面?如果有人可以提供一个简单的改进伪代码,那就太好了.

Is there a "standard" way of doing such things, especially in terms of efficiency, performance? if anyone can provide a simple improved pseudocode, that'd be great.

此外,我是否需要担心实现连接池以节省资源并加快程序速度?如果是这样,在这种情况下我该如何实现?

In addition, do I need to worry about implementing Connection Pooling, to conserve resource and speed up the program? If so, how do I implement it in this case?

谢谢!

推荐答案

与其添加变量,不如做一个类?

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

并在每个节点上执行一个 sql 查询

And execute an sql query on each

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

这篇关于在 C# 中处理多个数据库连接的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)