C# 在web服务中从SQL Server检索多个字段?
我正在测试如何在Web服务中从SQL Server检索数据。我正在VS2010中使用SQLServer2008R2,asp.NETWeb服务应用程序项目模板 假设我有一个表,有4列,没有任何常量(为了对话)C# 在web服务中从SQL Server检索多个字段?,c#,.net,web-services,sql-server-2008,asmx,C#,.net,Web Services,Sql Server 2008,Asmx,我正在测试如何在Web服务中从SQL Server检索数据。我正在VS2010中使用SQLServer2008R2,asp.NETWeb服务应用程序项目模板 假设我有一个表,有4列,没有任何常量(为了对话) 名字 姓氏 电子邮件 大学 如果用户为FirstName输入值,我希望能够获取SQL表的所有值。稍后,我会将FirstName更改为NTID或某个有意义的列。现在,如果用户键入FirstName,我的web服务只返回一个值,比如LastName 作为web服务的新手,我正在尽可能多地学习
- 名字
- 姓氏
- 电子邮件
- 大学
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;
}
}
}
这是我的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);
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Web.Services;
命名空间EmployeeRecs
{
///
///服务1的摘要说明
///
[WebService(命名空间=”http://tempuri.org/")]
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
//要允许使用ASP.NET AJAX从脚本调用此Web服务,请取消注释以下行。
//[System.Web.Script.Services.ScriptService]
公共类服务1:System.Web.Services.WebService
{
//创建新的web方法以获取员工姓氏
[网络方法]
公共字符串GetEmployee(字符串名)
{
返回DataHelper.GetEmployee(firstName);
}
}
}
除了SQL注入之外,还有几件事:
创建DataContract并为要返回的数据创建模型
[DataContract]
public class Employee
{
[DataMember]
public int NTID { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public int FirstName { get; set; }
}
用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;
}
//创建新方法以基于名字获取员工记录
公共静态列表GetEmployee(字符串名)
{
//创建连接
SqlConnection con=newsqlconnection(@“数据源=myDBServer;初始目录=MyDataBase;集成安全性=true;”);
//Sql命令
SqlCommand cmd=new SqlCommand(“从员工中选择NTID、LastName、FirstName,其中FirstName='”+FirstName.ToUpper()+“'”,con);
//开放连接
con.Open();
列出员工=新列表();
//从SQL Server读取
SqlDataReader dr=cmd.ExecuteReader();
while(dr.Read())
{
var employee=新员工{
NTID=dr[“NTID”].ToString();
LastName=dr[“LastName”].ToString();
FirstName=dr[“FirstName”].ToString();
};
employees.Add(employees);
}
//密切联系
Close博士();
con.Close();
返回员工;
}
公开它:
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);
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Web.Services;
命名空间EmployeeRecs
{
///
///服务1的摘要说明
///
[WebService(命名空间=”http://tempuri.org/")]
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
//要允许使用ASP.NET AJAX从脚本调用此Web服务,请取消注释以下行。
//[System.Web.Script.Services.ScriptService]
公共类服务1:System.Web.Services.WebService
{
//创建新的web方法以获取员工姓氏
[网络方法]
公共列表GetEmployee(字符串名)
{
返回DataHelper.GetEmployee(firstName);
}
}
}
OP为后代提供的完整代码:
这可能对其他在同样情况下挣扎的人有用。因此,我发布了解决方案的代码:
在VS2010中创建一个新的WCF项目,我使用了.net版本3.5,并在WCF模板下选择了WCF服务库
这是我在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; }
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Runtime.Serialization;
使用System.ServiceModel;
使用系统文本;
命名空间WcfServiceLibrary1
{
//注意:您可以使用“重构”菜单上的“重命名”命令同时更改代码和配置文件中的接口名称“IService1”。
[服务合同]
公共接口IService1
{
[经营合同]
列表GetEmployee(字符串firstName);
[经营合同]
CompositeType GetDataUsingDataContract(CompositeType composite);
//TODO:在此处添加服务操作
}
//卡斯顿数据合同
[数据合同]
公营雇员
{
[数据成员]
公共字符串名{get;set;}
[数据成员]
公共字符串LastName{get;set;}
[数据成员]
公共字符串电子邮件{get;set;}
[数据成员]
公共字符串{get;set;}
}
//使用下面示例中所示的数据协定将复合类型添加到服务操作中
[数据合同]
公共类复合类型
{
布尔布尔值=真;
string stringValue=“Hello”;
[数据成员]
公共布尔布尔值
{
获取{返回布尔值;}
设置{boolValue=value;}
}
[数据成员]
公共字符串字符串值
{
获取{return stringValue;}
设置{stringValue=value;}
}
}
}
这是我在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;
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Runtime.Serialization;
使用System.ServiceModel;
使用系统文本;
使用系统数据;
使用System.Da