MySqlCommand参数不工作MySqlCommand Parameter not Working

- 此内容更新于:2014-12-30
主题:

在以下代码,用于获取一个产品在一个特定的列表,该命令只返回结果当我硬编码(连接)productLine SQL。则不会发生参数替代。

原文:

In the following code, used to get a list of products in a particular line, the command only returns results when I hard code (concatenate) productLine into the SQL. The parameter substitution never happens.

            + "lineName = '@productLine' "                       
            + "and isVisible = 1 ";
        MySqlDataAdapter adap = new MySqlDataAdapter(sql, msc);
        adap.SelectCommand.Parameters.Add("@productLine", productLine);
解决方案:
删除撇号(')。 改变@ ?前缀的参数在MySql查询。
原文:
        + "lineName = ?productLine "                       
        + "and isVisible = 1 ";
    MySqlDataAdapter adap = new MySqlDataAdapter(sql, msc);
    adap.SelectCommand.Parameters.Add("?productLine", productLine);
  1. Remove the apostrophes (').
  2. Change @ to ?, which is the prefix of parameters in MySql queries.
ProfK的回复:谢谢范Kloeten先生。

(原文:Thank you Mr. van Kloeten.)

解决方案:
删除撇号(拼写吗?)。周围的的参数。他们应该不需要。
原文:

Remove the apostrophes (spelling?). The ' around the parameter. They should not be needed.

Rob Stevenson-Leggett的回复:如果他们值是一个字符串。

(原文:If they value is a string they are.)

Robert的回复:必须马克备份以来实际上海报是正确的和Stevenson-Leggett先生是错误的吗

(原文:Had to mark back up since actually the poster is correct and Mr Stevenson-Leggett is mistaken)

Sunny Milenov的回复:答案是正确的。Rob使一个错误在他的评论。

(原文:The answer is right. Rob makes a mistake in his comment.)

Rune Grimstad的回复:这是一个重要参数。你不要# 39;t担心封装字符串或格式化日期和这一切。

(原文:That is an important point about parameters. You don't have to worry about encapsulating strings or formatting dates and all that.)

解决方案:
就像他说的 应该是 +“lineName = @productLine”
原文:

like he said

+ "lineName = '@productLine' "

should be

+ "lineName = @productLine "
解决方案:
没错,这永远不会发生 “lineName = @productLine” 试一试 “lineName = @productLine”而不是@productLine已经被宣布为字符串类型的引号秘密将被添加。然而实际上是传递字符串@productLine而不是变量的值。
原文:

That's correct it never happens you have

  • "lineName = '@productLine' "

try

  • "lineName = @productLine " instead as @productLine will already be declared as a string type the quotes will be added secretly. You however are actually passing the string @productLine and not the variable value.