I am currently working on my C ++ project using Qt. I have MySQL as a database repository, and the idea is to make a small messenger like MSN and Skype.
However, my MySQL queries do not work. He just does not get any results or gives me an error. I'm sorry that the code is loading there.
This is my mysql.cpp that creates and opens a database connection:
#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(); }
The connection is opening. This is working correctly.
This is my mysql_result.cpp, the file I use to add parameters, insert, get results, etc .:
#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() { }
Well, that should work. If I have the following code, it correctly returns the entire first_name from the database:
mysql_result res = _mysql->create_result("SELECT * FROM members"); QSqlQuery qry = res.get_query(); while (qry.next()) { qDebug() << qry.value("first_name"); }
In member_controller.cpp (the class I use to retrieve members by name / id), I got the following:
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, "", "", "", "", ""); }
What he does, he will go to else, and I will get an error with invalid syntax next to: ID. If I replace: ID with @ID (as in C #), it will go to else without an error code. I do not know what's the problem.
Two things. The code needs to be slightly optimized and made easier, I will work on it. Also, is it possible / allowed to put the code in pastebin and embed the URL instead of entering the code here?