0

我想搜索在我的文本框中输入的字符的名称的empid。使用通配符。我写了声明

da = new SqlDataAdapter(
 "Select empID from emp where FirstName like ' "+textbox1.text+" ' % "
   , connstring); 
da.Fill(ds);

这个说法正确吗?

4

3 回答 3

1

您对sql-injection开放,请sql-parameters改用:

string sql = "SELECT empID " +
              "FROM emp " + 
              "WHERE FirstName like @FirstName";
using(var con = new SqlConnection(connstring))
using (SqlCommand command = new SqlCommand(sql, con))
{
    command.Parameters.AddWithValue("@FirstName",  textbox1.text + "%");
    using(var da = new SqlDataAdapter(command))
    {
        da.Fill(ds);
    }
}

% 符号需要作为参数值的一部分,使用绑定参数时根本不需要单引号。

于 2013-04-01T17:52:44.723 回答
1

您输入的语句将允许在通配符搜索之前的名字前面和名字后面有空格。如果你想搜索名字的任何部分,你应该把你的 SQL 改成这样:

SELECT empID FROM emp WHERE FirstName LIKE '@FirstName%'

此外,使用这样的参数化查询比仅仅连接你的参数更安全:

StringBuilder sb = new StringBuilder();
sb.Append("SELECT empID FROM emp WHERE FirstName LIKE '@FirstName%'");

SqlConnection conn = new SqlConnection(connStr);
SqlCommand command = new SqlCommand(sb.ToString());
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("FirstName", textbox1.Text);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);

如果要使用存储过程,则需要像这样设置 SqlCommand 对象:

SqlCommand command = new SqlCommand("Procedure", conn);
command.CommandType = Command.StoredProcedure;
于 2013-04-01T17:55:29.740 回答
0

这种说法有很多错误之处。

最简单的一个是您的单引号和文本框值之间有空格,而百分号超出了它需要的位置。还有,textbox1.text拼写错误。它应该更接近:

da = new SqlDataAdapter(
 "Select empID from emp where FirstName like '"+textbox1.Text+"%' ", connstring); 

但这只是第一个问题。 更大的问题是这是 SQL 注入的主要候选者。 请参阅参数化查询如何帮助防止 SQL 注入?

于 2013-04-01T17:51:17.437 回答