I try to separate database code from main application code. I have module with public class MySQLData and the static methods therein. Ther is a method listed below:
Code: Select all
.....
public class ParametersList
{
private string PName;
private object PValue;
public ParametersList(string pm, object pv)
{
this.PName = pm;
this.PValue = pv;
}
#region Properties
public string ParameterName // usually id field
{
get { return this.PName;}
set { this.PName = value; }
}
public object Value // any string field
{
get { return this.PValue;}
set { this.PValue = value; }
}
#endregion
}
......
public static IDataReader SelectSQL(string CmdName, ParametersList[] pl)
{
MySqlConnection cnn = new MySqlConnection (AppConfig.AppSettings["ConnectionString"]);
IDataReader idr = null;
MySqlCommand mcd = new MySqlCommand(CmdName, cnn);
mcd.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < pl.Length; i++)
mcd.Parameters.Add(pl[i].ParameterName,pl[i].Value);
try
{
cnn.Open();
idr = mcd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception Err)
{
MessageBox.Show("MySQL Error: " + Err.Message);
}
return idr;
}
Code: Select all
private void btnTest_Click(object sender, EventArgs e)
{
string strTest=null;
ParametersList[] pl = new ParametersList[1];
IDataReader midr = null;
pl[0] = new ParametersList("myid", 456);
midr=MySQLData.SelectSQL("test", pl);
while(midr.Read()) strTest+=midr.GetValue(2).ToString();
midr.Close();
MessageBox.Show(strTest);
}
The question is WHY ?
I use CommandBehavior.CloseConnection and theoretically the connection must be closed.