使用 C++ .Net MySQL 连接器的参数化查询 Returns 没有结果

Parameterized Query Returns no Results using C++ .Net MySQL Connector

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

但是,这个returns没有结果。如果我通过 MySQL 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");

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

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