我试图将数据插入QtSql数据库,但我一直收到错误:
"Parameter count mismatch"
我可能做错了什么?
#include <QtSql>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << QSqlDatabase::drivers();
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("LOCALHOST");
db.setDatabaseName("people");
db.setUserName("root");
db.setPassword("");
if(db.open()) {
qDebug() << "Opened!";
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();
if( !query.exec() )
qDebug() << query.lastError().text();
else
qDebug( "Inserted!" );
db.close();
} else {
qDebug() << "Not opened";
}
}
答案 0 :(得分:2)
您在数据库中没有名为person
的表。您正在尝试将值插入到不存在的表中。
我认为错误信息是错误的。但无论如何,我在代码中添加了CREATE
语句,以便在执行INSERT
语句之前创建表:
#include <QtSql>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if(!db.open()){
qDebug() << "Not opened";
return 1;
}
qDebug() << "Opened!";
QSqlQuery query;
//CREATE the table before executing the INSERT statement
query.exec("CREATE TABLE person (id INTEGER, forename TEXT, surname TEXT);");
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");
if( !query.exec() )
qDebug() << query.lastError().text();
else
qDebug( "Inserted!" );
return 0;
}
现在打印Inserted!
。但是如果我注释掉CREATE
语句行,我会在你的问题中得到同样的错误:
" Parameter count mismatch"