You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt 4.13.1中SQL插入语句参数数量不匹配问题求助

问题排查与解决

核心问题1:SQL语句字段与参数数量不匹配

你的INSERT语句中,目标表projet的字段列表仅有9个,但VALUES部分写了10个参数,直接触发参数计数不匹配:

  • 表字段:ID, theme, participant, classe, annee, jury, note, taux_de_completion, Description(共9项)
  • VALUES参数::ID, :theme, :participant, :classe, :annee, :encadreur, :jury, :note, :taux, :description(共10项)

你误将表中jury字段的位置替换为:encadreur,但表字段里并不存在encadreur,同时多了一个参数项。需修正SQL语句,让字段数量与VALUES参数数量一致:

  • 若表中没有encadreur字段,删除VALUES里的:encadreur;
  • 若表中存在encadreur字段,将其加入字段列表。

假设表中无encadreur字段,修正后的SQL语句:

qry.prepare("INSERT INTO projet (ID, theme, participant, classe, annee, jury, note, taux_de_completion, Description) VALUES(:ID, :theme, :participant, :classe, :annee, :jury, :note, :taux, :description);");

核心问题2:参数绑定拼写错误

绑定参数时你写的是:partcipant,但SQL语句里的参数是:participant(少了一个字母i),会导致该参数未被正确绑定,进一步加重参数计数问题。修正拼写:

qry.bindValue(":participant", participant);

完整修正后的代码片段

db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:/Users/Overlord/Documents/Qt Project/Projet_de_Genie_Logiciel/database.db");
if(db.open()){
    QSqlQuery qry(db);
    qry.prepare("INSERT INTO projet (ID, theme, participant, classe, annee, jury, note, taux_de_completion, Description) VALUES(:ID, :theme, :participant, :classe, :annee, :jury, :note, :taux, :description);");
    qry.bindValue(":theme", theme);
    qry.bindValue(":participant", participant);
    qry.bindValue(":ID", 4);
    qry.bindValue(":classe", classe);
    qry.bindValue(":annee", annee);
    qry.bindValue(":jury", jury);
    qry.bindValue(":note", note);
    qry.bindValue(":taux", taux);
    qry.bindValue(":description", description);
    if(!qry.exec()){
        QSqlError er = qry.lastError();
        qDebug() << er.text();
    }
    db.close();
}

额外建议

  • 始终在db.open()后判断连接状态,避免数据库未打开时执行后续逻辑;
  • 数据库操作完成后调用db.close()释放连接;
  • 可通过qDebug() << qry.executedQuery()查看实际执行的SQL语句,便于排查参数绑定问题。

内容的提问来源于stack exchange,提问作者Perez Mezuto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:15:39