我已经设置了这样的数据库,并确认正在从名为“person”的表中成功添加和读取记录:
db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("localhost");
db.setDatabaseName("testDatabase.db");
if (db.open()){
checkTableExists("person"); //see below
QSqlQuery query;
query.exec("create table person (id int primary key, "
"firstname varchar(20), lastname varchar(20))");
query.exec("insert into person values(101, 'Danny', 'Young')");
query.exec("insert into person values(107, 'Christine', 'Holand2')");
query.exec("insert into person values(103, 'Lars', 'Gordon')");
query.exec("insert into person values(104, 'Roberto', 'Robitaille')");
query.exec("insert into person values(105, 'Maria', 'Papadopoulos')");
checkTableExists("person"); //see below
QSqlQuery query2("SELECT lastname FROM person");
while (query2.next()) {
QString lastname = query2.value(0).toString();
qDebug()<<lastname;
}
}else{ //handle problem }
现在要了解有关QSqlQuery上各种属性的更多信息,我制作了这个我目前仅用于调试的函数:
bool checkTableExists(QString tablename)const{
QString sqlQuery = QString("SELECT name FROM testDatabase.db WHERE type =:table AND name = :tablename ");
QSqlQuery query;
bool prepare=query.prepare(sqlQuery);
query.bindValue(":table", "table");
query.bindValue(":tablename", tablename);
bool isExec=query.exec();
qDebug()<<"prepare: "<<prepare;
qDebug()<<"exec: " << isExec;
qDebug()<<"first: " << query.first();
qDebug()<<"isSelect: " << query.isSelect();
qDebug()<<"isValid: " << query.isValid();
qDebug()<<"isActive: " << query.isActive();
qDebug() << "next:" << query.next();
qDebug()<< "nextResult: "<<query.nextResult();
qDebug()<<"numRowsAffectd: "<<query.numRowsAffected();
return query.next();
}
当我运行上述内容时,我得到:
prepare: false
exec: false
first: false
isSelect: false
isValid: false
isActive: false
next: false
nextResult: false
numRowsAffectd: -1
prepare: false
exec: false
first: false
isSelect: false
isValid: false
isActive: false
next: false
nextResult: false
numRowsAffectd: -1
"Young"
"Holand"
"Gordon"
"Robitaille"
"Papadopoulos"
"Holand2"
在创建表之前和之后,这些属性都不会返回true,为什么会这样?