我想从webservice返回特定记录。我成功完成的工作仍然是通过以下代码得到所有记录:
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'.
请帮帮我..
答案 0 :(得分:0)
更改
Emailid = "test@test.com";
到
Emailid = "'test@test.com'";
请注意额外的单引号arount emailid
答案 1 :(得分:0)
首先,你应该使用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 ...
答案 2 :(得分:0)
不知道这是否会导致我没有使用C#一段时间
我认为你的错误就在这部分
select * from tblusers where EmailAddress=" + Emailid
尝试将其更改为
"select * from tblusers where EmailAddress='" + Emailid + "'"
答案 3 :(得分: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);