【发布时间】:2012-07-12 19:54:58
【问题描述】:
我正在测试如何在 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 注入
-
最好使用存储过程,而不是内联sql查询
-
@Nemo SqlCommand cmd = new SqlCommand("mystoredprocedurename", con); cmd.CommandType = CommandType.StoredProcedure;
-
SqlCommandBuilder.DeriveParameters(vCmd); vCmd.Parameters["@firstname"].Value = firstName;
-
谢谢内森。我将尝试使用 Stored Proc 并让您知道它是如何进行的。
标签: c# .net web-services sql-server-2008 asmx