[英]Retrieve Multiple fields from SQL Server in a web service?
I m testing how to retrieve data from SQL Server in Web Service. 我正在测试如何从Web Service中的SQL Server检索数据。 I m using SQL Server 2008 R2, asp.net web service application project template in VS 2010. 我在VS 2010中使用SQL Server 2008 R2,asp.net Web服务应用程序项目模板。
Let's say I have a table that has 4 columns and w/o any constaints(for the sake of conversation). 假设我有一个包含4列且没有任何constaints的表(为了对话)。
I want to be able to get all the values of my SQL table if a user inputs value for FirstName. 如果用户输入FirstName的值,我希望能够获取我的SQL表的所有值。 Later I would change FirstName to NTID or some meaningful column.Right now my web service just returns single value let's say LastName if a user types in FirstName. 稍后我会将FirstName更改为NTID或一些有意义的列。现在我的Web服务只返回单个值,如果用户键入FirstName,则说LastName。
Being a new to web services, I m trying to learn as much as I can and would greatly appreciate your time and effort in helping me out. 作为一名新的网络服务,我尽可能多地学习,并非常感谢您花时间和精力帮助我。 TIA. TIA。
Where/how do I make changes at my code below 我在下面的代码中在哪里/如何进行更改
Here's is my Data helper class 这是我的数据助手类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace EmployeeRecs
{
public class DataHelper
{
//create new method to get Employee record based on First Name
public static string GetEmployee(string firstName)
{
string LastName = "";
//Create Connection
SqlConnection con = new SqlConnection (@"Data Source=myDBServer;Initial Catalog=MyDataBase;Integrated Security=true;");
//Sql Command
SqlCommand cmd = new SqlCommand("Select LastName from Employees where FirstName ='" + firstName.ToUpper() + "'", con);
//Open Connection
con.Open();
//To Read From SQL Server
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
LastName = dr["LastName"].ToString();
}
//Close Connection
dr.Close();
con.Close();
return LastName;
}
}
}
And here's my asmx.cs class 这是我的asmx.cs类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace EmployeeRecs
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.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
{
//Create new web method to get Employee last name
[WebMethod]
public string GetEmployee(string firstName)
{
return DataHelper.GetEmployee(firstName);
}
}
}
Besides the SQL injection, a few things: 除了SQL注入之外,还有一些事情:
Create a DataContract and create a model for the data you want to return 创建DataContract并为要返回的数据创建模型
[DataContract]
public class Employee
{
[DataMember]
public int NTID { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public int FirstName { get; set; }
}
Fill that model with your SQL Query results and return it from your service 使用SQL查询结果填充该模型并从服务中返回
//create new method to get Employee record based on First Name
public static List<Employee> GetEmployee(string firstName)
{
//Create Connection
SqlConnection con = new SqlConnection (@"Data Source=myDBServer;Initial Catalog=MyDataBase;Integrated Security=true;");
//Sql Command
SqlCommand cmd = new SqlCommand("Select NTID, LastName, FirstName from Employees where FirstName ='" + firstName.ToUpper() + "'", con);
//Open Connection
con.Open();
List<Employee> employees = new List<Employee>();
//To Read From SQL Server
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var employee = new Employee {
NTID = dr["NTID"].ToString();
LastName = dr["LastName"].ToString();
FirstName = dr["FirstName"].ToString();
};
employees.Add(employee);
}
//Close Connection
dr.Close();
con.Close();
return employees;
}
Expose it: 揭露它:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace EmployeeRecs
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.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
{
//Create new web method to get Employee last name
[WebMethod]
public List<Employee> GetEmployee(string firstName)
{
return DataHelper.GetEmployee(firstName);
}
}
}
Full Code from OP for posterity: OP的完整代码用于后代:
This might be useful to other folks struggling with the same situation. 这可能对其他在相同情况下苦苦挣扎的人有用。 So I m posting my code for the solution: Create a new WCF PRoject in VS 2010, I used .net version 3.5 and selected WCF Service Library under WCF template. 所以我发布了解决方案的代码:在VS 2010中创建一个新的WCF PRoject,我使用.net版本3.5并在WCF模板下选择了WCF服务库。
Here's my code under IService1.cs 这是我在IService1.cs下的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WcfServiceLibrary1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
List<Employee> GetEmployee(string firstName);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
//Custon Data contract
[DataContract]
public class Employee
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string University { get; set; }
}
// Use a data contract as illustrated in the sample below to add composite types to service operations
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}
And here's my code under Service1.cs 这是我在Service1.cs下的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace WcfServiceLibrary1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
public class Service1 : IService1
{
public List<Employee> GetEmployee(string firstName)
{
//Create Connection
SqlConnection con = new SqlConnection(@"Data Source=gsops4;Initial Catalog=MultiTabDataAnalysis;Integrated Security=true;");
//Sql Command
SqlCommand cmd = new SqlCommand("Select LastName, FirstName, Email, University from Employees where FirstName ='" + firstName.ToUpper() + "'", con);
//Open Connection
con.Open();
List<Employee> employees = new List<Employee>();
//To Read From SQL Server
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var employee = new Employee {
FirstName = dr["FirstName"].ToString(),
LastName = dr["LastName"].ToString(),
Email = dr["Email"].ToString(),
University = dr["University"].ToString()
};
employees.Add(employee);
}
//Close Connection
dr.Close();
con.Close();
return employees;
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.