【问题标题】:how to get particular record by using where condition in webservice?如何通过使用 web 服务中的 where 条件获取特定记录?
【发布时间】:2012-10-04 05:49:04
【问题描述】:

我想从网络服务返回一条特定的记录。我仍然成功的是,通过以下代码获取所有记录:

 SqlConnection con;
    SqlDataAdapter adap;
    DataSet ds;
    [WebMethod]
    public DataSet Getmember()
    {

        con = new SqlConnection(@"Data Source=SQLDOTNET\MSSQLSERVER2008;Initial Catalog=doctor;Persist Security Info=True;User ID=sa;pwd=test123#;");
        adap = new SqlDataAdapter("select * from tblusers", con);
        ds = new DataSet();
        adap.Fill(ds, "tblusers");
        return ds;
    }

现在我想通过 Emailid 获取特定记录,因为我尝试了以下代码:

SqlConnection con;
    SqlDataAdapter adap;
    DataSet ds;
    [WebMethod]
    public DataSet Getmember(String Emailid)
    {
        Emailid = "test@test.com";
        con = new SqlConnection(@"Data Source=SQLDOTNET\MSSQLSERVER2008;Initial Catalog=doctor;Persist Security Info=True;User ID=sa;pwd=test123#;");
        adap = new SqlDataAdapter("select * from tblusers where EmailAddress=" + Emailid, con);
        ds = new DataSet();
        adap.Fill(ds, "tblusers");
        return ds;
    }

但是这段代码抛出了以下错误:

System.Data.SqlClient.SqlException: Invalid column name 'test@test.com'.

请帮帮我..

【问题讨论】:

标签: c# asp.net sql-server web-services


【解决方案1】:

您需要在 SQL 中将字符串文字括在单引号中:

"select * from tblusers where EmailAddress = '" + Emailid + "'"

但这会使您容易受到 SQL 注入攻击,因此不建议这样做。(检查如果将 Emailid 设置为 "' OR 1=1 OR ''='" 会发生什么情况。)

您应该指定Emailid 作为参数值:

var cmd = new SqlCommand("select * from tblusers where EmailAddress = ?");
cmd.Parameters.Add(Emailid);
adap = new SqlDataAdapter(cmd, con);

【讨论】:

    【解决方案2】:

    改变

    Emailid = "test@test.com";
    

    Emailid = "'test@test.com'";
    

    注意 emailid 周围多余的单引号

    【讨论】:

      【解决方案3】:

      不知道这是否会有所帮助,因为我已经有一段时间没有使用 C#了

      我认为你的错误发生在这部分

      select * from tblusers where EmailAddress=" + Emailid
      

      试试改成

      "select * from tblusers where EmailAddress='" + Emailid + "'"
      

      【讨论】:

        【解决方案4】:

        首先你应该使用 SQL 参数...不是普通的 SQL 查询,所以最好检查SQL Parameters

        adap = new SqlDataAdapter("select * from tblusers where EmailAddress=" + Emailid, con);
        

        应该改为

        adap = new SqlDataAdapter("select * from tblusers where EmailAddress='" + Emailid + "'", con);
        

        你错过了在你的查询中有“'”..你最好看看statement syntax...

        【讨论】:

          猜你喜欢
          • 2021-04-07
          • 2019-06-03
          • 1970-01-01
          • 2019-12-22
          • 1970-01-01
          • 2020-09-08
          • 2020-01-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多