QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":temp:");
if (!db.open()) {
qDebug() << "Database open error." << db.lastError();
return;
}
QSqlQuery query(db);
query.prepare("create table if not exists dew (id int, title varchar(255) not null)");
if (!query.exec()) {
qDebug() << "Query exec error. " << query.lastError();
return;
}
qDebug() << "Insert query exec OK";
if (!query.exec("insert into dew(id, title) values (1, 'hello')")) qDebug() << query.lastError();
Shows the output as
Insert query exec OK
QSqlError(1, "Unable to execute statement", "table dew has no column named id")
Insertion finished.
Table creation seems to be OK. But where is id field? I’m confused with this code. I test query.record().contains(“id”); and it is false
":temp:"is not a valid name for a temporary database, this creates a regular database on disk which stays after the database connection is closed.To create a temporary or an in-memory sqlite database, that won’t be saved to a file, you need to pass respectively an empty string (*) or the special string
":memory:"as the database name.http://www.sqlite.org/inmemorydb.html
Qt doesn’t allow an empty
QStringas the database name, but aQStringstarting with a'\0'should work:db.setDatabaseName(QChar(0));