简体   繁体   中英

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:

  1. serial is deprecated method of having identity column. use generated as identity instead.

  2. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM