处理同时连接到数据库两次

Handling with connecting to the database twice in the same time

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

有办法解决这个问题吗?

` 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();
    }`

您应该将 Connection cn = new Connection(); 移动到 class 范围

并移动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();
    }
}

将连接实例移出您的方法,以防止在每次计时器调用中创建它(即创建一个 class 或在父 class 中使用连接实例)。然后你可以在连接前用 State 属性 检查连接状态(参见 OleDbConnection.State)并在阅读你的查询后关闭它。

另一种(肮脏的)方法是用 try ... catch 语句包装您的代码块。