Problem with % n *** %n in writable segment detected *** C++ i Qt - c++

Problem with % n * %n in writable segment detected * C++ i Qt
I have program that process big data, that can't be modified. In one file we encounter "100% na" and application stop.
When I checked it with debuger, it return * %n in writable segment detected *.
I can't change visible that data, user must see "100% na". I thought of inserting some whitespace other then space after %.
Rewriting the whole applications is not a point. It runs on Windows and Linuks.
Currently the problem is in this code. I checked this in other places and it was the same. The variables are QStrings.
QSqlQuery query;
query.exec("insert into table_name ("+variable_with_columns_names+" values ("+variable_with_data_to_insert+");");
Do you have any ideas how to evade it?
edit
Prepare the query solved the problem in this spot. But it is breaking in others points. Update , Select ... where ...='100% na'(as variable), generating reports and other stuff. Whats more that this data is used by at least 5 modules, each using more then 5 data tables. So I will wait sometime, if anyone have other solution.
PS. One more question:
Why is "% n" interpreted as "%n", when it shouldn't?
Funny thing is if I change "100% na" to "100%% na", I get in data base "100%% na" when it should be changed to "100% na".

Use prepare to prepare the query. Then insert the values using bindValue. Prepared statements should always be used in such scenarios, as they handle the escaping of special characters for you.

QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
query.bindValue(0, 1001);
query.bindValue(1, "Bart");
query.bindValue(2, "Simpson");
query.exec();
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");
query.exec();
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (?, ?, ?)");
query.bindValue(0, 1001);
query.bindValue(1, "Bart");
query.bindValue(2, "Simpson");
query.exec();
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (?, ?, ?)");
query.addBindValue(1001);
query.addBindValue("Bart");
query.addBindValue("Simpson");
query.exec();
any of these help?

Related

Qt PostgreSQL foreign key issue

I've created a table which is called user_parameters in Qt Creator. While I was trying to give a reference to another table which is cities. I faced with a syntax error. My snippet for using foreign key and error are given bellow. How can I solve this error? Thx for your helping.
QSqlQuery query;
query.exec("CREATE TABLE user_parameters "
"(id SERIAL primary key, "
"firstname varchar(50), "
"lastname varchar(50), "
"age integer, "
"username varchar(50), "
"password varchar(100), "
"cityID integer references cities(id))");
QSqlQuery insertQuery;
int last_id = maxIdValue() + 1;
insertQuery.prepare("INSERT INTO user_parameters (id, firstname, lastname, age, username, password, cityID)"
"VALUES(:id, :firstname, :lastname, :age, :username, :password, :cityID)");
insertQuery.bindValue(":id", last_id);
insertQuery.bindValue(":firstname", fName);
insertQuery.bindValue(":lastname", lName);
insertQuery.bindValue(":age", age);
insertQuery.bindValue(":username", userName);
insertQuery.bindValue(":password", password);
insertQuery.bindValue(":cityID", cityID);
QSqlError("42601", "QPSQL: Unable to create query", "ERROR: syntax error at or near "("\nLINE 1: EXECUTE (1, 'Name', 'Surname', 22, 'userName', 'password', 1)\n ^\n(42601)")
your query looks ok to me , however you might be missing a space before "values" keyword.also two side notes :
serial is deprecated method of having identity column. use generated as identity instead.
serial/ identity columns are managed by sql engine, you can avoid getting max value and insert it each time.
so :
insertQuery.prepare("INSERT INTO user_parameters (firstname, lastname, age, username, password, cityID) "
"VALUES(:firstname, :lastname, :age, :username, :password, :cityID)");
notice the space at the end of first line

C++ Query builder for SPARQL queries

This is my first post in stack-overflow, so sorry in advance for possible "bad practices".
Context: the goal is to send SPARQL queries through http-requests to a GraphDB data base.
Problem: to construct the queries on code in a safe way. Currently done by means of std::string dummyStr = "Hello"+" World" or dummyStr.append("bla") (I was told this was not safe due to XSS, but thats not the issue here)
Question: do you know any query builder library for doing this string concatenation?
A search for C++ query builder on the web returned this answer.
After implementing the approach with the suggested Qt QSqlQuery class, I'm able to ".prepare" the query, but not to ".bindValue".
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.open();
QSqlQuery startQuery;
/*Prepare query*/
startQuery.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
startQuery.bindValue(":id", 1001);
startQuery.bindValue(":forename", "Bart");
startQuery.bindValue(":surname", "Simpson");
/*convert query to std::string*/
QString startQueryString = startQuery.lastQuery();
std::string dummyQuery = startQueryString.toUtf8().constData();
Why can't I bind the values to the placeholders?
Is it because I have no "actual" database, but rather a dummy-database just to construct the query?
My actual Query looks something like this:
SELECT ?s WHERE { FILTER(STRSTARTS(STR(?s),":referenceIRI")). ?s rdf:type rdfs:Class.}
And I would like to treat :referenceIRI as a placeholder.
I've searched overall to try to overcome this problem, as I just need the query-builder functionality.
Also: on my actual SPARQL query I have both ? and :myVal elements, which are the 2 types of placeholders in QSqlQuery for binding values. Any idea on how to by-pass the ? placeholder and just consider the :myVal-type?

Qt - GUI Database programming

I am using Qt GUI to save data in MySQL using C++.
I am using QDateTimeEdit widget for this. Whatever the value changed by user in GUI of QDateTimeEdit, it should be inserted in MySQL.
Can anyone tell me how to do that?
How to access value from QDateTimeEdit and converting it in proper format like QString and using MySQL query inserting it into database?
An alternative is not to convert it to a QString but let the driver do that for you. If you expect some precision in the conversion some cases this might be better, other cases it can be worse:
QDateTime date = ui->dateTimeEdit->dateTime();
QSqlQuery query(myDatabase);
query.prepare("INSERT INTO my_table (id, date) "
" VALUES (:id, :date)");
query.bindValue(":id", 1001);
query.bindValue(":date", date);
query.exec();
The QSqlQuery::bindValue() function will take the QDateTime and pass it through as a QVariant and then the driver should know how to convert a QVariant::DateTime to the correct string that the database understands.
About second part "how to access value":
You somehow in code created object of QDateTimeEdit and place it on some layout. Typically it will be pointer with name for example mpDTPicker.
QDateTimeEdit * mpDTPicker = new QDateTimeEdit();
//place mpDTPicker on layout.
For access current time we need use method dateTime:
//User actions with date -> emitted signal -> execute slot with our logic
{
QDateTime momentum = mpDTPicker->dateTime();
// So here we need convert QDateTime to QString and we will use [toString Method](http://doc.qt.io/qt-4.8/qdatetime.html#toString)
QString result_string = momentum.toString("dd:mm:yy");
QDebug() << result_string;
}
So that is all about converting QDateTime to QString.
About first part of Question how to get that user changed value of DateTimeEdit is total another question.
And about third part how to store it in mysql database everything depended on structure of your table. But typicaly it can be solved with simple query:
QSqlQuery query;
QString mQuerry = "INSERT INTO mytable (id, date) VALUES (0, \"" +result_string "\" )";
query.exec(mQuerry);
And please READ DOCS especial when them so cool :)

Database creation error in Qt

I am using this code to create a database. But I am getting "false" in debug. I tried a lot but its not working. What is the error in this?
QSqlQuery query;
qDebug() << query.exec("CREATE TABLE glucose (id INTEGER PRIMARY KEY AUTOINCREMENT, value INTEGER, date TEXT, time TEXT, duration TEXT, note TEXT");
qDebug() << query.prepare("INSERT INTO glucose(id, value, date, time, duration, note)""VALUES(?, ?, ?, ?, ?, ?)");
query.bindValue(1,edit_glucose->text().toInt());
query.bindValue(2,datetime->date());
query.bindValue(3,datetime->time());
query.bindValue(4,"a");
query.bindValue(5,edit_note->toPlainText());
qDebug() << query.exec();
you forget to close your CREATE TABLE query with ")"
QSqlQuery has the method lastError(), returns error information :)
You are passing in the INSERT query the id field. You must remove it.
The query should be:
Debug() << query.prepare("INSERT INTO glucose(value, date, time, duration, note)
VALUES(?, ?, ?, ?, ?)");

Inserting binary data via QSQL

How to insert binary data to table "test" from "database" with 2 columns text "name" and bin "pic"
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
db.setUserName("user");
db.setPassword("pwd");
db.setPort(1234);
db.setDatabaseName("database");
You can have a look at http://www.java2s.com/Code/Cpp/Qt/UsingsqldatabasefromQt.htm snippets
First you need to open the DB db.open();
One way would be
QSqlQuery query;
query.prepare("INSERT INTO test (name, pic) "
"VALUES (:name, :pic)");
query.bindValue(":name", "Bart");
query.bindValue(":pic", "Bart.jpg");
query.exec();