简体   繁体   English

Qt PostgreSQL 外键问题

[英]Qt PostgreSQL foreign key issue

I've created a table which is called user_parameters in Qt Creator.我在 Qt Creator 中创建了一个名为 user_parameters 的表。 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)") 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. serial 是不推荐使用的具有标识列的方法。 use generated as identity instead.使用generated as identity

  2. serial/ identity columns are managed by sql engine, you can avoid getting max value and insert it each time.序列/标识列由 sql 引擎管理,您可以避免获取最大值并每次都插入它。

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注意第一行末尾的空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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