我一直在尝试从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]的索引,那么我可以读取一个值,但它甚至不是第一个,所以我不明白为什么它会错误地读取我的数据库。朝着正确方向提出的任何提示,甚至我的代码中的更正都将受到赞赏。
答案 0 :(得分:0)
获得单个结果(由订购决定):
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;
}