tots tots - 28 days ago 20
ASP.NET (C#) Question

asp.net C# DB Class

i am trying to learn ASP.NET but i am stuck when it comes to DB connections how can i create db connection class for oledbDataReader.
please help me guys im new in asp.net C# can you correct my code?

public class AccessDb
{
OleDbConnection con = new OleDbConnection();

private OleDbCommand m_cmd = new OleDbCommand();
public OleDbCommand Command
{
get { return m_cmd; }
}

public AccessDb()
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
}

public IDataReader ExecReader(string sql)
{
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}

this.m_cmd.CommandText = sql;

if (this.m_cmd.Connection == null)
{
this.m_cmd.Connection = con;
}

this.m_cmd.CommandType = CommandType.Text;
return this.m_cmd.ExecuteReader();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
}

Answer

Change your return code as below and don't close the connection in your final block.

return this.m_cmd.ExecuteReader(CommandBehavior.CloseConnection):
Comments