我如何创建executeReader类

时间:2014-08-25 07:30:22

标签: c#

爵士

我有一个ExecuteNonquery的连接类

public class Connection
{
    SqlConnection conn;
    SqlCommand cmd;

    public void connclose()
    {
        conn.Close();
    }
    public Connection()
    {
       conn = new SqlConnection(@"server=ADMIN-PC;database=sample;Integrated security=true");
       cmd = null;
    }
    public void nonquery(SqlCommand cmd)
    {
        conn.Open();
        cmd.Connection = conn;
        cmd.ExecuteNonQuery();
        conn.Close();

    }

以同样的方式,我也必须创建一个Executereader类......我应该为此应用哪些更改

我也有一节课

public void insert(string sid, string cid, string state)
    {

        SqlCommand cmd = new SqlCommand("InsertState");
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@StateId", SqlDbType.VarChar).Value = sid;
        cmd.Parameters.Add("@CountryId", SqlDbType.VarChar).Value = cid;
        cmd.Parameters.Add("@State", SqlDbType.VarChar).Value = state;

        conn.nonquery(cmd);

    }

1 个答案:

答案 0 :(得分:0)

您可以添加此方法

public SqlDataReader ReadMe(SqlCommand cmd)
    {
        conn.Open();
        cmd.Connection = conn;
        SqlDataReader reader =  cmd.ExecuteReader();
        return reader;
    }

您可以这样称呼它:

   SqlCommand cmd = new SqlCommand("reading");
   cmd.CommandType = CommandType.StoredProcedure;
   using(SqlDataReader ourreader = conn.ReadMe(cmd))
        {
         while (ourreader.Read())
               {
               //some code
               }
        }
   conn.Close();