ProfK
ProfK

Reputation: 51064

MySqlCommand Parameter not Working

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);

Upvotes: 3

Views: 3046

Answers (4)

Omer van Kloeten
Omer van Kloeten

Reputation: 11980

        + "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.

Upvotes: 7

Robert
Robert

Reputation: 1845

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.

Upvotes: 0

Ian G
Ian G

Reputation: 30234

like he said

+ "lineName = '@productLine' " 

should be

+ "lineName = @productLine " 

Upvotes: 0

Rune Grimstad
Rune Grimstad

Reputation: 36310

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

Upvotes: 2

Related Questions