【发布时间】:2011-07-30 17:35:52
【问题描述】:
我想从我的 Web 服务方法返回一个格式为“abc#xyz#ghi#tru”(其中 # 是分隔符)的字符串数组。但是我做不到。这是我当前的网络服务代码:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace WebService10
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 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 Service1 : System.Web.Services.WebService
{
String[] result=new String[40];
String[] result2 = new String[40];
[WebMethod]
public String[] getData()
{
SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
try
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
myCommand.CommandText = "select count(*) from names where name =@name";
SqlDataReader myReader = myCommand.ExecuteReader();
//while
for(int i=0;i<40;i++)
{
if (myReader.Read())
{
result[i]= myReader["name"].ToString();
result2[i] = result[i] + "#";
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
myConnection.Close();
}
return result2;
}
}
}
谁能告诉我我的代码有什么问题?
【问题讨论】:
-
那是很多代码。它在做什么?如果您将 getData() 更改为仅返回一个静态值,例如“返回的字符串”,会发生什么?{
-
嘿,对不起,我会解释的。我在 SQL Server 2008 中创建了一个数据库,其中有一个“名称”列,我在其中插入了示例值。我只想以我在问题中提到的形式以及分隔符来检索这些值。有什么办法吗?
-
你想从你的单列中获取所有的名字吗?
-
@kleinohad:是的,我有单列“名称”,其中包含我已经插入的值。我现在只需要按照我在帖子中提到的方式使用我的网络服务的方法来检索它们
-
是否有充分的理由用“#”而不是标准逗号分隔? (因为您可以依靠网络服务为您序列化您的数组,而不是进行字符串连接)
标签: .net web-services visual-studio-2008