2011-03-03 41 views
4

我正在使用ODBC连接到Sybase数据库。问题是即使在作用域完成后连接也没有关闭,并且当我运行sp_who时,我发现数据库中有大约200个连接打开。我试图启用连接池,但这也没有帮助。如何关闭.NET ODBC连接?

using(var connection = GetOdbcConnection()) 
    { 
     connection.Open(); 
     using (var cmd = new OdbcCommand(query, connection)) 
     { 
      var reader = cmd.ExecuteReader(); 
      if (reader.Read()) 
      { 
       long textLen = reader.GetChars(0, 0, null, 0, 0); 
      } 
      reader.Close(); 
     } 
    } 

我使用的连接字符串是value="Driver={Adaptive Server Enterprise};app=xxx;server=xxxx;port=xxxx; db=xxx;uid=xxx;pwd=xxxx;textsize=2097152"

更新:

public static OdbcConnection GetOdbcConnection() { 
    string connectionString = ConfigurationManager.AppSettings["ConnectionString"].ToString(); 
    return new OdbcConnection(connectionString); 
} 
+0

GetOdbcConnection是做什么的? – Bobby 2011-03-03 08:53:32

+0

public static OdbcConnection GetOdbcConnection() string connectionString = ConfigurationManager.AppSettings [“ConnectionString”]。ToString(); 返回新的OdbcConnection(connectionString); } – 2011-03-03 09:00:21

回答

3

你试过connection.Close()

using(var connection = GetOdbcConnection()) 
    { 
     connection.Open(); 
     using (var cmd = new OdbcCommand(query, connection)) 
     { 
      var reader = cmd.ExecuteReader(); 
      if (reader.Read()) 
      { 
       long textLen = reader.GetChars(0, 0, null, 0, 0); 

      } 
      reader.Close(); 
     }    
     // Close the connection 
     connection.Close(); 
    } 
+5

通常这不应该成为问题,因为'Close'和'Dispose'在'OdbcConnection'-Object中是同义词。它应该在'using'范围的末尾自动调用。 – Bobby 2011-03-03 08:55:05

+0

yes尝试了这一点,但它没有帮助 – 2011-03-03 08:56:01

+1

然后,也许有其他方法打开连接但不使用using语句并忘记明确调用.Close()。正如鲍比所说,使用应该关闭连接。 – Peter 2011-03-03 08:58:53

0

尝试将尝试.. catch和finally ...

在最后明确检查connection.state没有关闭..关闭它..

+0

转换using语句由编译器将其与try/finally语句完全相同的IL。 – 2011-03-03 09:30:14

+0

是的正确,但编译器不会自动关闭连接... – sajoshi 2011-03-03 10:20:34

0

连接到数据库将当using块结束时自动关闭。你根本不需要做任何事情。

+1

nope不帮助,我仍然可以看到连接后,当我运行sp_who活动 – 2011-03-03 08:58:11

0

我不确定,但我认为GetOdbcConnection函数是罪魁祸首。尝试此功能的修改版本。

private static OdbcConnection _Connection; 
public static OdbcConnection GetOdbcConnection() { 
    string connectionString = 
     ConfigurationManager.AppSettings["ConnectionString"].ToString(); 
    _Connection = new OdbcConnection(connectionString); 
    return _Connection; 
}