以下是转载:
QT5 QSqlQuery的SELECT INSERT UPDATE DELETE命令用法
select查询:
QSqlQuery q("SELECT * FROM departments"); QSqlRecord rec = q.record(); int idCol = rec.indexOf("departID"); // 这样获取保险一点。index of the field "departID" int nameCol=rec.indexOf("department");// index of the field "department" QList<QString> listStrDepartID;//部门编号列表 QList<QString> listStrDepartment;//部门名称列表 listStrDepartID.clear();//清空列表内容 listStrDepartment.clear();//清空列表内容 while (q.next()) { listStrDepartID<<q.value(idCol).toString();//获取表departments中的"departID"字段数据 listStrDepartment<<q.value(nameCol).toString();//获取表departments中的"department"字段数据 }
insert插入:
QSqlQuery query; //新建departID记录内容 query.prepare("INSERT INTO departments (departID,department) " "VALUES (:departID,:department)"); query.bindValue(":departID",strNewDepartmentNum); query.bindValue(":department",ui->dbEditNewDepartmentName->text()); query.exec();
update更新、修改:
QSqlQuery query; //更新departID处对应的department内容 query.prepare("UPDATE departments SET department =:department WHERE departID =:departID "); query.bindValue(":departID",ui->dbEditModifyDepartmentNum->text()); query.bindValue(":department",ui->dbComboModifyDepartmentName->currentText()); query.exec();
delete 删除:
QSqlQuery query; //删除departID记录内容 query.prepare("DELETE FROM departments WHERE departID =:departID "); query.bindValue(":departID",ui->dbEditDeleteDepartmentNum->text()); query.exec();
以下是总结:
insert插入那里使用qsqldatabase的事务操作,提速300%:
db.transaction(); sql.exec(insert into...); // 执行后提交 db.commit();
获取最新插入的id:
db.lastInsertId().toInt()
一个QSqlQuery要执行多次sql的话,最好先调用finish(),然后再exec()。就是说每次exec()之后调用finish()也是个保险的做法。
另外,如果你前面prepare的时候使用了占位符,例如":myName,:yourName",不管是update还是insert,都要对应bindValue,否则,他会把你旧的数据给清空掉,对,就是这么任性!