gpt4 book ai didi

c# - 在 Web 服务中从 SQL Server 检索多个字段?

转载 作者:太空狗 更新时间:2023-10-30 00:20:29 24 4
gpt4 key购买 nike

我正在测试如何在 Web 服务中从 SQL Server 检索数据。我在 VS 2010 中使用 SQL Server 2008 R2、asp.net Web 服务应用程序项目模板。

假设我有一个包含 4 列且没有任何约束(为了便于对话)的表格。

  • 名字
  • 姓氏
  • 电子邮件
  • 大学

如果用户输入 FirstName 的值,我希望能够获取我的 SQL 表的所有值。稍后我会将 FirstName 更改为 NTID 或一些有意义的列。现在,如果用户输入 FirstName,我的 Web 服务只返回单个值,假设是 LastName。

作为 Web 服务的新手,我正在努力学习尽可能多的知识,非常感谢您花时间和精力帮助我。 TIA。

我在哪里/如何对下面的代码进行更改

这是我的数据助手类

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);

}
}
}

最佳答案

除了SQL注入(inject),还有一些事情:

创建一个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;
}

暴露它:

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);

}
}
}

OP 的完整代码供后代使用:

这可能对其他遇到同样情况的人有用。所以我发布了我的解决方案代码:在 VS 2010 中创建一个新的 WCF PRoject,我使用的是 .net 3.5 版并在 WCF 模板下选择了 WCF Service Library。

这是我在 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; }
}
}
}

这是我在 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;
}
}
}

关于c# - 在 Web 服务中从 SQL Server 检索多个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com