【问题标题】:Trying to read data from sql database in asp.net web service尝试从 asp.net Web 服务中的 sql 数据库中读取数据
【发布时间】:2018-07-26 16:00:07
【问题描述】:

我一直在尝试从 asp.net Web 服务 .asmx 页面中的本地数据库获取数据,但我只得到一个元素,甚至没有第一个元素。当我尝试另一个索引时,我得到的索引超出了数组异常的范围,但我知道这不是因为我的数据库比我尝试的任何索引都大。

这是我当前的 .asmx 代码

    <%@ WebService Language="C#" Class="PostWebService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]

public class PostWebService  : System.Web.Services.WebService {
    int result;
    [WebMethod]
    public int GetRates() {
        //try
        //{
            SqlConnection connection = new SqlConnection(@"Data Source = (local); Initial Catalog =  RatesDB; Integrated Security=True");
            SqlCommand cmd = new SqlCommand(" select HeartRate from Rates order by HeartRate DESC", connection);
            connection.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            int i = 0;
            while (dr.Read())
            {
                result = Convert.ToInt32(dr[i++]);
                Console.WriteLine(result);
            }
            dr.Close();
            connection.Close();
        //}
        //finally
        //{ 

        //}
        return result;
    }
}

我一直在使用代码来尝试获得不同的结果,但我不断收到错误:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Data.SqlClient.SqlDataReader.CheckDataIsReady(Int32 columnIndex, Boolean allowPartiallyReadColumn, Boolean permitAsync, String methodName)
   at System.Data.SqlClient.SqlDataReader.TryReadColumn(Int32 i, Boolean setTimeout, Boolean allowPartiallyReadColumn)
   at System.Data.SqlClient.SqlDataReader.GetValueInternal(Int32 i)
   at System.Data.SqlClient.SqlDataReader.GetValue(Int32 i)
   at System.Data.SqlClient.SqlDataReader.get_Item(Int32 i)
   at PostWebService.GetRates() in C:\Users\Rommel\Desktop\Website\Website\Website\PostWebService.asmx:line 28

如果我使用 0 作为 dr[0] 的索引,那么我可以读取一个值,但它甚至不是第一个值,所以我不明白为什么它读取我的数据库不正确。任何正确方向的提示,甚至我的代码中的更正都将不胜感激。

【问题讨论】:

  • dr[i] 获取当前行上列号i + 1 的值(所以dr[0] 是第一列)。随着i++ 不断增加i,如果行数多于列数,您将尝试读取不存在的列,这将导致异常。
  • 您只会得到一个结果,因为您只会返回一个结果 - 您会覆盖循环中的 result 变量,因此最终您会返回您看到的最后一行的值。如果要返回 n 行,则需要返回某种类型的集合。
  • 感谢您的快速回复。为什么它获取列的值而不是行的值?即使那样,如果我使用dr [0],为什么它不返回第一个元素?我应该如何解决这个问题?
  • 由于您要返回一个 int,因此您只需要一个结果。那是哪一个?第一行,最后一行,还是什么?决定并改用 ExecuteScalar。
  • dr[i] 读取 columns(横向)而不是 rows(向下),在循环内 dr[0] 是第一列,即 HeartRate,当前行的。如果您将 dr[i++] 更改为 dr[0] 您应该在查询结果中为每一行打印一行。

标签: c# asp.net web-services


【解决方案1】:

获取单个结果(由排序决定):

public int GetRate()
{
    int i = -1; // an impossible value
    try
    {
        using (SqlConnection connection = new SqlConnection(@"Data Source=(local);Initial Catalog=RatesDB;Integrated Security=True"))
        using (SqlCommand cmd = new SqlCommand(@"select top(1) HeartRate 
                   from Rates 
                   order by HeartRate DESC", connection))
        {
            connection.Open();
            i = Convert.ToInt32(cmd.ExecuteScalar());
            connection.Close();
        }
    }
    catch
    { }
    return result;
}

从一列中获取多个值:

public List<int> GetRates()
{
    var result = new List<int>();
    try
    {
        using (SqlConnection connection = new SqlConnection(@"Data Source=(local);Initial Catalog=RatesDB;Integrated Security=True"))
        using (SqlCommand cmd = new SqlCommand(@"select HeartRate 
                   from Rates 
                   order by HeartRate DESC", connection))
        {
            connection.Open();
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                result.Add((int)rdr[0]);
            }
            connection.Close();
        }
    }
    catch
    { }
    return result;
}

【讨论】:

  • 是的,谢谢,正是我所需要的。感谢大家的帮助!
猜你喜欢
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多