我正在让一个Web服务从sql服务器获取数据。我需要从 sql 服务器获取许多字段,但我只能获取一个字段,即当前名称
namespace WebApplication2
{
public class DataHelper
{
public static string GetCurrency(string currencyCode)
{
string currencyName = "";
SqlConnection con = new SqlConnection(@"Data Source=WEB3SHAREPOINT;Initial Catalog=WSS_Search_WEB3;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select PO_NUMBER,PO_STATUS from View_1 where PO_HEADER_ID ='" + currencyCode.ToUpper() + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
currencyName = dr["PO_NUMBER"].ToString();
}
dr.Close();
con.Close();
return currencyName;
}
}
}
我需要从查询中获取PO_Number和 PO 状态
据我了解,您不仅需要返回PO_NUMBER,还需要返回PO_STATUS,并且据我了解,您希望返回这两个值。
我建议你制作代表你想要返回的模型。
为此,我们创建一个模型类来调用它,例如 POModel:
public class POModel
{
public string currencyName { get; set; } // PO_Number
public string statusName { get; set; } // PO_Status
}
然后像您一样从SQL中获取值并返回对象而不是字符串。
在这里,您的最终代码看起来像,当然是命名以及所有您可以更改方式(如果最适合(的内容:
public class DataHelper
{
public static POModel GetCurrency(string currencyCode)
{
//string currencyName = "";
var poModel = new POModel();
SqlConnection con = new SqlConnection(@"Data Source=WEB3SHAREPOINT;Initial Catalog=WSS_Search_WEB3;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select PO_NUMBER,PO_STATUS from View_1 where PO_HEADER_ID ='" + currencyCode.ToUpper() + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
poModel.currencyName = dr["PO_NUMBER"].ToString();
poModel.statusName = dr["PO_STATUS"].ToString();
}
dr.Close();
con.Close();
//return currencyName;
return poModel;
}
}
public class POModel
{
public string currencyName { get; set; }
public string statusName { get; set; }
}
一种选择是返回包含这两个值的数组。string[]
通知:
public static string[] GetCurrency(string currencyCode)
类似于你声明string currencyName = "";
的方式,而是创建一个数组变量:
string[] poData = new string[2];
由于这看起来应该返回一行,所以我不会循环。只需做一个Read()
:
dr.Read();
poData[0] = dr["PO_NUMBER"].ToString(); //poData[] will have to be declared in your method
poData[1] = dr["PO_STATUS"].ToString();
....
return poData;