user1215114
user1215114

Reputation: 13

MySqlCommand seems not to be passing parameters

The code below seems not to be inserting the parameter value to the query (nothing is returned by the query). If I test that query in the DB (of course instead of the ?author parameter I type the passed value and some rows are returned. Why ?

   var conn = new MySqlConnection(connectionString);

   MySqlCommand comm = new MySqlCommand("", conn);

   comm.Parameters.Add(new MySqlParameter("?author", author)); //I've also tried AddWithValue method

   comm.CommandText = .....;

            conn.Open();
            MySqlDataReader myReader = comm.ExecuteReader();

            try
            {
                while (myReader.Read())
                {
                    //unreachable code because nothing is returned
                }
            }
            catch
            {
                myReader.Close();
                conn.Close();
                categoriesList.Clear();
            }
            finally
            {
                myReader.Close();
                conn.Close();
            }

Upvotes: 1

Views: 2103

Answers (2)

John Woo
John Woo

Reputation: 263723

Since you are using MySQLCommand don't add ? in parameter's name:

if you have query like this:

comm.CommandText = "INSERT INTO tableName(colA) VALUES (@param1)";
comm.CommandType = CommandType.Text;

then you have to do this this:

comm.Parameters.AddWithValue("param1", "yourValue");

UPDATE

Assuming you have query with LIKE condition:

"SELECT * FROM WHERE colA Like '%value%'"

then try this:

comm.CommandText = "SELECT * FROM WHERE colA Like CONCAT('%', @param1, '%'");
comm.Parameters.AddWithValue("param1", "yourValue");

Upvotes: 1

ethorn10
ethorn10

Reputation: 1899

It might be as simple as the .CommandText needs to be before the .Parameters.Add statements. So:

   comm.CommandText = .....;
   comm.Parameters.Add(new MySqlParameter("?author", author)); //I've also tried AddWithValue method

Upvotes: 0

Related Questions