2

我想从我的表中读取一个 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);
       } 
4

3 回答 3

3

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

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

顺便说一句,最好使用创建命令对象sqlc.CreateCommand()- 它创建适当的命令并自动为其分配连接。

于 2013-11-30T07:13:32.233 回答
2

使用此代码

  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"))
            }
        }

}
于 2013-11-30T07:15:14.910 回答
2

您没有分配connection object sqlcSqlCommand.

添加这个:

 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();
于 2013-11-30T07:15:15.037 回答