参数化查询使用C ++ .Net MySQL Connector返回无结果

时间:2015-08-01 19:12:52

标签: c++ mysql parameterized-query

我似乎无法独自找到解决这个问题的方法。我使用这个泛型函数从数据库中检索数据,如下所示: int id = 29 ArrayList^ classes = getClassesGeneric("dep_id", "=", id.ToString());

但是,这不会返回任何结果。如果我通过My​​SQL Workbench查询数据库或没有参数,它可以正常工作。我错过了什么?

    ArrayList^ Accessor::getClassesGeneric(String^ col, String^ op, String^ value)
    {
            ArrayList^ result = gcnew ArrayList();
            this->cmd = gcnew MySqlCommand("SELECT * FROM rpos_db.classes WHERE @col @op @value;", this->con);
            try
            {
                this->cmd->Parameters->AddWithValue("@col", col);
                this->cmd->Parameters->AddWithValue("@op", op);
                this->cmd->Parameters->AddWithValue("@value", value);
                this->cmd->Prepare();
                MySqlDataReader^ r = this->cmd->ExecuteReader();

                while (r->Read())
                {
                    Class^ c = gcnew Class();

                    c->id = r->GetInt32(0);
                    c->dep_id = r->GetInt32(1);
                    c->name = r->GetString(2);
                    c->code = r->GetString(3);

                    result->Add(c);
                }
                r->Close();
            }
            catch (Exception^ ex)
            {
                MessageBox::Show(ex->StackTrace, ex->Message);
            }
            return result;
    }

使用这样的函数会产生缩进结果: classes = getClassesGeneric("1", "=", "1");

1 个答案:

答案 0 :(得分:0)

参数只能用于替换文字,而不能替换对象名称或句法元素,例如=运算符。你要么必须硬编码。如果要动态传递它们,则必须使用字符串操作:

ArrayList^ Accessor::getClassesGeneric(String^ col, String^ op, String^ value)
{
        ArrayList^ result = gcnew ArrayList();
        this->cmd = gcnew MySqlCommand
                    ("SELECT * FROM rpos_db.classes WHERE " + 
                     col + " " + op + " @value;", this->con);
        try
        {
            this->cmd->Parameters->AddWithValue("@value", value);
            this->cmd->Prepare();
            MySqlDataReader^ r = this->cmd->ExecuteReader();