0

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

 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'.

请帮我..

4

4 回答 4

0

改变

Emailid = "test@test.com";

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

注意 emailid 周围的额外单引号

于 2012-10-04T05:53:33.853 回答
0

一开始你应该使用 SQL 参数......不是普通的 SQL 查询,所以最好检查SQL 参数

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

应该改为

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

你错过了在你的查询中有“'”..你最好看看语句语法......

于 2012-10-04T05:53:56.647 回答
0

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

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

select * from tblusers where EmailAddress=" + Emailid

尝试将其更改为

"select * from tblusers where EmailAddress='" + Emailid + "'"
于 2012-10-04T05:54:37.737 回答
0

您需要在 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);
于 2012-10-04T05:55:30.097 回答