首页 > 解决方案 > 处理同时连接两次数据库

问题描述

我正在使用一个计时器,它每 1ms 导致一次与数据库的连接,当有时它在前一个连接关闭之前连接到数据库时,这会导致问题。

有没有办法处理这个问题?

` protected void timerTest_tick(object sen, EventArgs e)
   {
            string sql = "SELECT * FROM [TableActions] WHERE ID =" + Session["LobbyID"];
            Connection cn = new Connection();
            OleDbDataReader reader = cn.GetReader(sql);
            if (reader.Read())
            {
                Session["GNACode"] = reader.GetString(2);
            }
            cn.closecon();
    }`

标签: c#oledbconnection

解决方案


你应该转移Connection cn = new Connection();到班级范围

并移动cn.closecon();以形成关闭事件。

public class YourForm{
   private static Connection cn = null;
   YourForm(){
     if (cn == null) 
     {
       instance = new Connection();
     }
   }
   protected void timerTest_tick(object sen, EventArgs e)
   {
            string sql = "SELECT * FROM [TableActions] WHERE ID =" + Session["LobbyID"];

            OleDbDataReader reader = cn.GetReader(sql);
            if (reader.Read())
            {
                Session["GNACode"] = reader.GetString(2);
            }

    }

    private void CloseEvent(){
       cn.closecon();
    }
}

推荐阅读