简体   繁体   中英

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();
    }
  }
}

如下更改您的返回码,并且不要在最后一个块中关闭连接。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM