如何使用QT插入SQL数据库表

时间:2019-01-26 20:13:07

标签: c++ qt

我正在尝试使用QT插入我的SQL数据库。我已成功使用其他SQL命令(如Delete)。但是这里什么都没有添加到我的数据库中。我想知道某个地方是否存在语法错误。

QSqlQuery task;

task.prepare("insert or replace into animals(name, type, breed, gender, age, lifespan, noise, intelligence, adaptability, personality, diet, environment, pastOwners, timeDedication, costDedication, medication, reproductability, appetite, energyLevel, weight, height) values ('" + name + "', '" + type + "','" + breed + "','" + gender + "', " + age + ", " + lifespan + ", " + noise + ", " + intelligence + ", " + adaptability + " ,'" + personality + "', '" + diet + "', '" + environment + "', " + pastOwners + ", " + timeDedication + ", " + costDedication + ", " + medication + ", " + reproductability + ", '" + appetite + "', " + energyLevel + ", " + weight + ", " + height + ");");

task.exec();

1 个答案:

答案 0 :(得分:3)

对于prepared query,您需要编写如下内容:

  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();

绑定值将有助于避免SQL注入。