如何使用executereader读取一个值

时间:2013-11-30 07:12:34

标签: c# asp.net sql executereader

我想从我的表中读取一个int值。但我遇到了错误 这是我的代码。请帮我编辑我的代码。

    sqlc = new SqlConnection(ConnectionString);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    string username = HttpContext.Current.User.Identity.Name.ToString();

    cmd.CommandText = @"SELECT RemainedCharge "
                              + " FROM aspnet_Users "
                              + " WHERE UserName = @UserName ";
    cmd.Parameters.Add(new SqlParameter("@UserName", username));
    //string RemainedCharge;
    sqlc.Open();

    SqlDataReader rdr = cmd.ExecuteReader();


       // loop over all rows returned by SqlDataReader
       while(rdr.Read())
       {
          RemainedChargeLbl.Text=rdr.GetString(0);
       } 

3 个答案:

答案 0 :(得分:3)

要读取一个值,您不需要读者。使用SqlCommand.ExecuteScalar Method执行查询并返回查询返回的结果集中第一行的第一列:

int value = (int)cmd.ExecuteScalcar();

BTW最好用sqlc.CreateCommand()创建命令对象 - 它会创建适当的命令并自动为其分配连接。

答案 1 :(得分:2)

使用此code

  using (var conn = new SqlConnection(SomeConnectionString))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = "SELECT RemainedCharge "
                                  + " FROM aspnet_Users "
                                  + " WHERE UserName = @UserName ";
        cmd.Parameters.Add(new SqlParameter("@UserName", username);
        cmd.Parameters.AddWithValue("@id", index);
        using (var reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
            }
        }

}

答案 2 :(得分:1)

您没有将connection object sqlc分配给SqlCommand

添加:

 cmd.Connection=sqlc;

完整解决方案:

sqlc = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection=sqlc;
string username = HttpContext.Current.User.Identity.Name.ToString();

cmd.CommandText = @"SELECT RemainedCharge "
                          + " FROM aspnet_Users "
                          + " WHERE UserName = @UserName ";
cmd.Parameters.Add(new SqlParameter("@UserName", username));
//string RemainedCharge;
sqlc.Open();

 RemainedChargeLbl.Text =((int) cmd.ExecuteScalar()).ToString();