QMYSQL查询失败

时间:2015-10-08 14:41:30

标签: c++ mysql qt

我目前正在使用Qt在C ++中处理我的项目。我有MySQL作为数据库存储,我的想法是建立一个像MSN和Skype这样的小型信使。

然而,我的MySQL查询失败了。它根本没有结果或给我一个错误。即将出现大量代码,对不起。

这是我的mysql.cpp,它创建并打开数据库连接:

#include "mysql.h"

mysql::mysql()
{
    this->db = QSqlDatabase::addDatabase("QMYSQL", "QMYSQL");
    this->db.setHostName("localhost");
    this->db.setUserName("root");
    this->db.setPassword("Eequi4");
    this->db.setDatabaseName("test");
    this->db.open();
}

mysql::~mysql()
{
}

mysql_result mysql::create_result(QString query)
{
    return mysql_result(this->db.exec(query));
}

QSqlError mysql::error()
{
    return this->db.lastError();
}

连接已打开。这是正常的。

这是我的mysql_result.cpp,我用来添加参数,插入,获取结果等文件:

#include "mysql_result.h"

mysql_result::mysql_result(QSqlQuery query)
{
    this->query = query;
}

void mysql_result::add_parameter(QVariant value)
{
    this->query.addBindValue(value);
}

void mysql_result::add_parameter(QString key, QVariant value)
{
    this->query.bindValue(key, value);
}

int mysql_result::get_last_id()
{
    return this->query.lastInsertId().toInt();
}

void mysql_result::execute()
{
    this->query.execBatch();
}

QSqlQuery mysql_result::get_query()
{
    return this->query;
}

mysql_result::~mysql_result()
{
}

好的,这应该有效。如果我有以下代码,它会正确返回数据库中的所有成员first_name:

mysql_result res = _mysql->create_result("SELECT * FROM members");
QSqlQuery qry = res.get_query();
while (qry.next())
{
    qDebug() << qry.value("first_name");
}

在member_controller.cpp(我用来按名称/ id检索成员的类)中,我得到了这个:

member* member_controller::get_member(int id)
{
    mysql_result result = engine::get_mysql().create_result("SELECT * FROM members WHERE member_id = :ID");
    result.add_parameter(":ID", id);
    QSqlQuery query = result.get_query();

    if (query.exec() && query.next())
    {
        return new member(id, query.value("first_name").toString(), query.value("second_name").toString(), query.value("screen_name").toString(), query.value("email").toString(), query.value("status").toString());
    }
    else
    {
        qDebug() << engine::get_mysql().error() << "\n";
        qDebug() << query.lastError() << "\n";
    }

    return new member(0, "", "", "", "", "");
}

它做什么会转到else,我得到错误无效语法附近:ID。如果我用@ID替换:ID(就像在C#中一样),它将转到其他没有错误代码的地方..我不知道问题是什么。

两件事。代码需要进行一些优化并变得更容易,我将继续努力。是否可以/允许将代码放入pastebin并粘贴URL而不是将代码放在这里?

1 个答案:

答案 0 :(得分:1)

尝试将您的查询更改为:

"SELECT * FROM members WHERE member_id = ?"

并添加你的参数:

result.add_parameter(0, id);

我还怀疑,if (query.exec() && query.next())不正确,我应该删除对.next()的检查,因为我认为这需要在结果集中存在另一条记录。

相关问题