首页 > 解决方案 > 如何同时与单个数据库建立多个 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 函数,但有没有更好的方法?

标签: c#asp.netoledbconnection

解决方案


我找到了解决此问题的方法,
我将类设为静态类并添加了打开和关闭函数,
只要它们被称为 int (默认为零)表示使用该类的位置数量要么递增,要么递减,
如果变为 0 我关闭连接,如果它为零并增加我打开连接。


推荐阅读