MySqlCommand似乎没有传递参数

时间:2012-02-17 02:15:52

标签: c# mysql

下面的代码似乎没有将参数值插入查询(查询不返回任何内容)。如果我在DB中测试该查询(当然而不是?author参数,我输入传递的值并返回一些行。为什么?

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

2 个答案:

答案 0 :(得分:1)

由于您使用MySQLCommand请勿在参数名称中添加?

如果您有这样的查询:

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

然后你必须这样做:

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

<强>更新

假设您有LIKE条件的查询:

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

然后试试这个:

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

答案 1 :(得分:0)

可能就像.CommandText需要在.Parameters.Add语句之前一样简单。所以:

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