Qt segmentation fault - c++

I must develop a social network simulator using C++ and QT library.
I store user into mysql database using QODBC.
When i run my application, i throw a SIGSEGV error.
here, my function which throw this error :
QMutex userMutex;
userMutex.lock();
QListIterator<User*> i(users);
User* user;
QString sql = "insert into t_user (id, pseudo, name, firstname, birthdate) values ";
QString bindValue = QString::fromStdString("(?, ?, ?, ?, ?),").repeated(users.count());
sql.append(bindValue);
QSqlQuery query = QSqlQuery(Interface::getCnx());
query.prepare(sql);
while(i.hasNext())
{
user = i.next();
query.addBindValue(QString::number(user->getId()));
query.addBindValue(user->getPseudo());
query.addBindValue(user->getName());
query.addBindValue(user->getFirstname());
QString birthdate = QString::number(user->getBirthDate().year()) + "-" + QString::number(user->getBirthDate().month()) + "-" + QString::number(user->getBirthDate().day());
query.addBindValue(birthdate);
}
query.exec();
userMutex.unlock();
It is "query.exec()" line which throw this error.
Do you see what's wrong?

First of all you have an extra comma here:
QString bindValue = QString::fromStdString("(?, ?, ?, ?, ?),").repeated(users.count());
So or you "repeat" string count-1 times and then add "(?, ?, ?, ?, ?)":
QString bindValue = QString::fromStdString("(?, ?, ?, ?, ?),").repeated(users.count() - 1);
bindValue "(?, ?, ?, ?, ?)";
Or you have to remove last char of your string bindValue.

I found the answer ... i guess.
This SIGSEGV error has disappeared when i decrease the size of the list.
Before the list contains 1000 users but now it constains only 800 users per call to this méthod.
Thanks for your help.

Related

How in Qt i can insert several queries into sql in one time?

In SQL, I have foreign keys in tables so my insert one by one doesn't work. How can I insert several queries in one time?
query.prepare("ISERT INTO job_format (job_format_id, location, work_schedule)"
"VALUES (:job_format_idValue, :locationValue, :work_scheduleValue)");
query.bindValue(":job_format_idValue", lastJobFormat + 1);
query.bindValue(":locationValue", ui->tableWidgetData->item(i,4)->text());
query.bindValue(":work_scheduleValue", ui->tableWidgetData->item(i,3)->text());
query.exec();
query.prepare("INSERT INTO vacancy (vacancy_id, salary, company_id, profession, job_format, contacts, experience) "
"VALUES (:vacancy_idValue, :salaryValue, :company_idValue, :professionValue, :job_formatValue, :contactsValue, :experienceValue)");
query.bindValue(":vacancy_idValue", lastVacancy + 1);
query.bindValue(":salaryValue", ui->tableWidgetData->item(i,5)->text());
query.bindValue(":company_idValue", currentID);
query.bindValue(":professionValue", ui->tableWidgetData->item(i,0)->text());
query.bindValue(":job_formatValue", lastJobFormat + 1);
query.bindValue(":contactsValue", ui->tableWidgetData->item(i,6)->text());
query.bindValue(":experienceValue", ui->tableWidgetData->item(i,1)->text());
query.exec();
query.prepare("INSERT INTO skills_for_vacancy (line_skills_for_vacancy_id, vacancy_id, skill) "
"VALUES (:line_skills_for_vacancy_idValue, :vacancy_idValue, :skill)");
query.bindValue(":line_skills_for_vacancy_idValue", lastLineSkill + 1);
query.bindValue(":vacancy_idValue", lastVacancy + 1);
query.bindValue(":skill", tableSkillsMas[i]);
query.exec();
This is my foreign keys
First line ISERT INTO not INSERT...

How to bind datetime function in sqlite3 c++

My sqlite insert statement is as
char *testSQL;
testSQL = "INSERT INTO Test (id, tx_time) VALUES ("+id+ ", datetime("+timestamp+",'unixepoch', 'localtime'));";
I'm trying to convert above into prepared statement using sqlite3_bind.
testSQL = "INSERT INTO Test (id, tx_time) VALUES (?, ?);";
I can bind id simply using sqlite3_bind_int(stmt, 1, id) but how can I bind datetime function?
Put the datetime in the SQL instead:
char *testSQL;
testSQL = "INSERT INTO Test (id, tx_time) "
"VALUES (?, datetime(?,'unixepoch', 'localtime'));"
And use sqlite3_bind_int to bind timestamp instead.

Escape % (percent) in QSqlQuery::addBindValue() for LIKE

I use an SQLite database with Qt. I bind the values to the query instead of passing them in the query string. However, I can't figure out how to properly escape a % (percent) in the bound value itself.
For example, how do I change this code so that it outputs va%ue1, but not value1?
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
db.open();
QSqlQuery q(db);
q.exec("CREATE TABLE test (field1)");
q.exec("INSERT INTO test VALUES (\"value1\")");
q.exec("INSERT INTO test VALUES (\"va%ue1\")");
q.prepare("SELECT field1 FROM test WHERE field1 LIKE ?");
q.addBindValue("va%%%");
q.exec();
while (q.next()) {
qDebug() << q.value(0);
}
Right now this outputs both:
QVariant(QString, "value1")
QVariant(QString, "va%ue1")
I also tried with q.addBindValue("va\\%%");, but it didn't output anything at all.
The LIKE pattern matching works on a different level than parameter binding.
To escape '%' or '_' characters, you must use the ESCAPE clause:
q.prepare("SELECT field1 FROM test WHERE field1 LIKE ? ESCAPE '#'");
q.addBindValue("va#%%");
Here's a function to escape any bound value:
QString sqlEscape(QString boundValue)
{
boundValue.replace('#', "##");
boundValue.replace('_', "#_");
boundValue.replace('%', "#%");
}

insert multiple char * into a const char* with pre filled text

i have setup a working mysql connector for my c++ project. Now i'm making a login for registered users.
i want to get the username and password into the SQLquery string.
i am trying to get this working:
currently its displaying noting and the game crashes.
#include "boost/lexical_cast.hpp" //boost
#include <cgl\cgl.h> // game library (core media library)
#include <sstream> // sstream
char* username=DEFSER;
char* password=PASS12345;
const char *SQLquery;
std::string SQLquery("SELECT * FROM Users WHERE UserName='" + boost::lexical_cast<std::string>(username) + "' AND PassWord='" + boost::lexical_cast<std::string>(password) + "'");
what i want to get out of SQLquery:
SELECT * FROM Users WHERE UserName='DEFSER' AND PassWord='PASS12345'
and i execute it in this way:
res = stmt->executeQuery(SQLquery);
this is not a fully working code i only want to know how i can get the username and password into the SQLquery.
error when i try to run the query:
Run-Time Check Failure #3 - The variable 'SQLquery' is being used without being initialized.
What you are doing is not concatenating strings, you are adding std::string objects to a literal string pointer.
The std::string class handles concatenation of C-style strings just fine without any lexical_cast, so just do e.g.
std::string SQLquery = "SELECT * FROM Users WHERE UserName='" +
username + "' AND PassWord='" + password + "'";
After testing the above solution doesn't actually work for me. But the following does:
std::string SQLQuery = (std::ostringstream() << "SELECT * FROM Users WHERE UserName='"
<< username << "' AND PassWord='" << password << "'").str();

C++ Mysql Real Escape String Issue

Hmm, for some reason, its only doing this on the first username (and password) and does it for how big my my vector is. Any ideas on why?
int eMysql::strip(string &input) {
char* from = new char[strlen(input.c_str()) * 3 + 1];
mysql_real_escape_string(&mysql, from, input.c_str(), input.length());
input = input.assign(from);
delete from;
}
Where its used:
if(query.size() > 0) {
mysql->strip(query[0]);
mysql->strip(query[1]);
mysql->query("SELECT `username` FROM `users` where `username` = '"+ query[0] +"';");
I suggest building the query as a separate string variable rather than passing the mess in the argument:
static const char fixed_text[] = "SELECT `username` FROM `users` where `username` = '";
std::string query_text(fixed_text);
query_text += query[0];
query_text += "';";
mysql->query(query_text);
This technique allows you to examine the query before it is sent to MySql.
I suggest you examine the query[0] variable for any strange characters such as \r and \n. The MySql manual has a section listing characters that need to be escaped.