上記のすべての例は、同じ弱点を示しています。 使用ステートメント は使用しません。 これにより、接続やその他の使い捨てオブジェクトを適切に閉じて廃棄することができます。 1つ以上のステートメントが例外をスローした場合、接続を閉じるコードは実行されず、接続が多すぎるというエラーで終了する可能性があります
例
string commandLine = "SELECT * FROM Table WHERE active=1";
commandLine = commandLine.Remove(commandLine.Length - 3);
using(MySqlConnection connect = new MySqlConnection(connectionStringMySql))
using(MySqlCommand cmd = new MySqlCommand(commandLine, connect))
{
connect.Open();
using(MySqlDataReader msdr = cmd.ExecuteReader())
{
while (msdr.Read())
{
//Read data
}
}
} // Here the connection will be closed and disposed. (and the command also)