c# - 如何同时与单个数据库建立多个 OleDb 连接
问题描述
我正在开发 Asp.net 中的应用程序。
我有一个处理数据库连接和查询的 DBHandler 类,
DBHandler 构造函数打开一个新的 OleDBConnection,DBHandler 的 Dispose 函数关闭并处理连接,通常这是可行的。
DBHandler 类的一些代码:
readonly OleDbConnection Con;
public DBHandler()
{
string cs = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
Con = new OleDbConnection(cs);
Con.Open();
}
public void Dispose()
{
Con.Close();
Con.Dispose();
Console.WriteLine("db.dispose");
}
我还有一些处理 get 和 post 请求的请求控制器/处理程序,
这里是一些示例代码:
public class CountryInfoHandler : HttpMessageHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, CancellationToken token)
{
HttpContent content;
HttpResponseMessage response = new HttpResponseMessage();
......
CountryInfo info = null;
using (DBHandler db = new DBHandler())
{
if (db.DoesCountryExist(parsedUri[3]))
{
info = db.Countries[parsedUri[3]];
}
else
{
info = null;
}
}
content = new StringContent(JsonConvert.SerializeObject(info));
content.Headers.ContentType.MediaType = "application/json";
response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = content
};
.....
return response;
}
}
除非同时出现多个需要调用数据库的请求,否则一切正常,当发生这种情况时,我会收到 System.Runtime.InteropServices.SEHException。
我猜这是由同时打开多个数据库连接引起的,有没有办法防止这种情况发生或有多个连接没有任何问题?
我目前正在考虑使它成为一个静态类,其中包含所有在单个连接上工作的 OpenConnection 和 CloseConnection 函数,但有没有更好的方法?
解决方案
我找到了解决此问题的方法,
我将类设为静态类并添加了打开和关闭函数,
只要它们被称为 int (默认为零)表示使用该类的位置数量要么递增,要么递减,
如果变为 0 我关闭连接,如果它为零并增加我打开连接。
推荐阅读
- python - 使用 Matplotlib 在一条线上选择 N 个点
- python - 类型对象不可下标
- rest - Shopware 6 产品 api
- javascript - 使用占位符值作为输入值
- java - 使用 Spring 在运行时从属性文件动态加载对象
- filter - Google Analytics:按自定义维度过滤
- php - 如何在 Sentry laravel 中 Cron 作业日志
- python - statsmodels SARIMAX 摘要中未显示差异术语
- c# - 通过一种方法存储的值无法在下一种方法中正确使用(C#)
- flutter - 我想在我的颤振应用程序中添加一个 SnackBar