Home  >  Article  >  Backend Development  >  How SqlHelper encapsulates SqlDataReader in c#

How SqlHelper encapsulates SqlDataReader in c#

高洛峰
高洛峰Original
2017-01-14 14:29:081789browse

The example of this article describes the method of encapsulating SqlDataReader by SqlHelper in c#. Share it with everyone for your reference. The details are as follows:

/// <summary>
/// 执行sql语句返回一个DataReader
/// 当返回DataReader的时候,注意:
/// 1.Connection不能关闭
/// 2.DataReader不能关闭
/// 3.command对象执行ExecuteReader()的时候需要传递一个参数CommandBehavior.CloseConnection
/// </summary>
/// <param name="sql"></param>
/// <param name="pms"></param>
/// <returns></returns>
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)
{
 SqlConnection con = new SqlConnection(constr);
 using (SqlCommand cmd = new SqlCommand(sql, con))
 {
  if (pms != null)
  {
   cmd.Parameters.AddRange(pms);
  }
  con.Open();
  //当调用ExecuteReader()方法的时候,如果传递一个CommandBehavior.CloseConnection参数,
  //则表示将来当用户关闭reader的时候,系统会自动将Connection也关闭掉。
  SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  return reader;
 }
}

I hope this article will be helpful to everyone’s C# programming.

For more related articles on how SqlHelper encapsulates SqlDataReader in c#, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn