Qt PostgreSQL foreign key issue - c++

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

Related

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1

#bot.message_handler(commands=['start'])
def start(m):
cid = m.chat.id
secret = id_generator()
hashedpw = hashlib.md5( secret ).hexdigest()
cur.execute("INSERT into `users` (username, password) VALUES (str(cid), str(hashedpw)")
bot.send_message(m.chat.id, "Your secret token is " + secret)
Can someone may help me in fixing this problem?
To be honest I have no idea what the problem could be.
You have an error in your SQL syntax
You're missing a closing parenthesis ) for VALUES:
cur.execute("INSERT into `users` (username, password) VALUES (str(cid), str(hashedpw))")
It is because you need to pass the actual parameters to the database, which would be quoted for strings - e.g.
cur.execute("INSERT into `users` (username, password) VALUES ('jon','passwd')")
Try something like, which will use the values in your variables:
cur.execute("INSERT into `users` (username, password) VALUES (?,?)", (str(cid), str(hashedpw)) )
this answer may help:
How to use variables in SQL statement in Python?

problems with django raw query parameters

I was trying to make a custom raw query for a model and i get this error:
DatabaseError: error de sintaxis en o cerca de
«E'positions_statusrecord'» LINE 1: SELECT id FROM
E'positions_statusrecord' WHERE "type"=E'Leav...
Here is the raw query i'm trying to use (it's a manager method):
def get_status_ids(self, model):
"""
This query returns the latest statuses ids for each entry
of "model" in StatusRecord.
"""
db_table = self.model._meta.db_table
model_type = model.get_status_type()
raw_query = (
"SELECT id "
"FROM %s "
"WHERE \"type\"=%s AND "
"(identifier,date_time) IN "
"( "
"SELECT identifier, Max(date_time) "
"FROM %s "
"WHERE \"type\"=%s "
"GROUP BY identifier"
")"
)
params = (db_table, model_type, db_table, model_type, )
return self.raw(raw_query, params)
I've tried with a simpler query (just a SELECT ... FROM ..) and had the same problem. It seems to be that raw queries couldn't have the FROM part completed with a parameter.
Am i right? or have i made a mistake and i'm not finding it?
I'm using postgreSQL 8.4.10, django 1.3 and python 2.6.
I've searched information about raw queries parameters to see if there are some forbidden formatting options, but i didn't find anything that helps me.
Does anyone knows what's causing this error?
It seems to be that raw queries couldn't have the "FROM" part completed with a parameter.
Yes, the ORM will quote the string argument making it ... FROM 'some_table' ....
Since the db_table parameter is trusted (not originated from user input), you can do something like:
raw_query = (
"SELECT id "
"FROM %s "
"WHERE \"type\"=%%s AND "
"(identifier,date_time) IN "
"( "
"SELECT identifier, Max(date_time) "
"FROM %s "
"WHERE \"type\"=%%s "
"GROUP BY identifier"
")"
) % (db_table, db_table)
return self.raw(raw_query, (model_type, model_type))
Since Django Aggregation can be used in filters, probably you can get the same results without resorting to raw SQL (look also the in lookup example).
Look if you can replace raw() with QuerySet.extra() and SQL IN with EXISTS.

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(?, ?, ?, ?, ?)");

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

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?

Subsequent insertion of records with QSqlTableRecord fail after first error

I have a problem with inserting data into SQLite database using QSqlTableModel. The table is created like this:
QSqlQuery createTblSMS("CREATE TABLE sms_tbl("
"isRead BOOLEAN NOT NULL,"
"readTime DATETIME,"
"arrivalTime DATETIME NOT NULL,"
"sender TEXT NOT NULL,"
"receiver TEXT NOT NULL,"
"smsContent TEXT,"
"PRIMARY KEY(arrivalTime, sender, receiver));");
I am inserting the records like this:
smsModel->insertRecord(-1, sms);
QString error = smsModel->lastError().text();
smsModel->submitAll();
smsModel is QSqlTableModel.
If i put for example a record wih this values (false, NULL, '2010-06-30 17:27:55', '075710383', 'ONE 142140', 'TOP 15 # 2') - the record is inserted.
After that record if put for example a record wih this values (false, NULL, '2010-06-30 10:05:29', '075710383', 'ONE 142140', 'TOP 15 # 3') - also this record is inserted.
But if i try to reinsert the record (false, NULL, '2010-06-30 17:27:55', '075710383', 'ONE 142140', 'TOP 15 # 2') which is already in the database, the smsModel will give an error like this :"columns arrivalTime, sender, receiver are not unique Unable to fetch row" - which is expected. Any other subsequent insertions of unique records will fail and the model gives me the same error. Do you have any clue why is this happening?
I ran into this problem of two fold.
When you are in manual submit mode, QSqlTableModel does not clear its cache when a submitAll fails (which it should when you send it a record that violates your constraints).
To correct this, you need to call either call select() or revertAll to remove those pending changes.
The doc doesn't make this very obvious, but it is there, check it out: http://doc.qt.io/qt-4.8/qsqltablemodel.html#submitAll
After a while i didn't manage to find solution with QSqlTableModel, so I made a workaround with QSqlQuery. The code is this:
QSqlQuery query(QSqlDatabase::database(mConnectionName));
query.prepare("INSERT INTO sms_tbl (isRead, readTime, arrivalTime,"
"sender, receiver, smsContent) "
"VALUES (:isRead, :readTime, :arrivalTime, "
":sender, :receiver, :smsContent)");
query.bindValue(":isRead", sms.value("isRead").toBool());
query.bindValue(":readTime", sms.value("readTime").toString());
query.bindValue(":arrivalTime", sms.value("arrivalTime").toString());
query.bindValue(":sender", sms.value("sender").toString());
query.bindValue(":receiver", sms.value("receiver").toString());
query.bindValue(":smsContent", sms.value("smsContent").toString());
query.exec();
You can't add a record with same primary key again. You have a primary key which contains the columns arrivalTime, sender, receiver. So you can't a value with same values of this three values.
You can change your create statement and a auto increment sms_table_id of type int.