我有一个简单的数据库管理器类(名字比它的能力更宏大):
class DbManager
{
private MySqlConnectionStringBuilder _connectionString;
public DbManager()
{
_connectionString = new MySqlConnectionStringBuilder();
_connectionString.UserID = Properties.Database.Default.Username;
_connectionString.Password = Properties.Database.Default.Password;
_connectionString.Server = Properties.Database.Default.Server;
_connectionString.Database = Properties.Database.Default.Schema;
_connectionString.MaximumPoolSize = 5;
}
public MySqlConnection GetConnection()
{
MySqlConnection con = new MySqlConnection(_connectionString.GetConnectionString(true));
con.Open();
return con;
}
}
我还有另一个类别代表数据库中其中一张表的记录,然后我通过如下方式填充这个类别:
class Contact
{
private void Populate(object contactID)
{
using (OleDbConnection con = DbManager.GetConnection())
{
string q = "SELECT FirstName, LastName FROM Contacts WHERE ContactID = ?";
using (OleDbCommand cmd = new OleDbCommand(q, con))
{
cmd.Parameters.AddWithValue("?", contactID);
using (OleDbDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
this.FirstName = reader.GetString(0);
this.LastName = reader.GetString(1);
this.Address = new Address();
this.Address.Populate(ContactID)
}
}
}
}
}
}
class Address
{
private void Populate(object contactID)
{
using (OleDbConnection con = DbManager.GetConnection())
{
string q = "SELECT Address1 FROM Addresses WHERE ContactID = ?";
using (OleDbCommand cmd = new OleDbCommand(q, con))
{
cmd.Parameters.AddWithValue("?", contactID);
using (OleDbDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
this.Address1 = reader.GetString(0);
}
}
}
}
}
}
现在我认为所有的
using
语句都会确保在完成后将连接返回到池中,以便下一个使用,但是我有一个循环,创建了数百个这些 Contacts 并填充它们,似乎连接没有被释放。连接、命令和读取器都在各自的
using
语句中。
populate
调用了另一个子对象的populate
。如果我将其注释掉,就没问题了。不过,子对象的populate
几乎和那个一样。 - Cylindric