SQL执行操作 QSqlQuery提供了对数据库记录的Select、Insert、Update、Delete操作。 SELECT操作:
QSqlQuery query;
query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
while (query.next()) {
QString name =query.value(0).toString();
int salary = query.value(1).toInt();
qDebug() << name << salary;
}
通过QSqlQuery::next() 下一条 QSqlQuery::previous() 上一条 QSqlQuery::first() 第一条 QSqlQuery::last() 最后一条 QSqlQuery::seek(),定位任意一条记录的位置。 列数、字段数:query.record().count() 行数,记录数 query.size(); sql="SELECT * FROM sys"; query.exec(sql); rec=query.record(); int numRows; while (query.next()) { if (db.driver()->hasFeature(QSqlDriver::QuerySize)) { //驱动支持返回记录数 numRows = query.size(); } else { //驱动不支持返回记录数,只能循环查找 query.last(); numRows = query.at() + 1; } } 值:query.value(0) INSERT操作:
//单一插入数据
QSqlQuery query;
query.prepare("INSERT INTO employee (id, name, salary) "
"VALUES (:id, :name, :salary)");
query.bindValue(":id", 1001);
query.bindValue(":name", "Thad Beaumont");
query.bindValue(":salary", 65000);
query.exec();
//批量插入数据
QSqlQuery query;
query.prepare("insert into myTable values (?, ?)");
QVariantList ints;
ints << 1 << 2 << 3 << 4;
query.addBindValue(ints);
QVariantList names;
names << "Harald" << "Boris" << "Trond" << QVariant(QVariant::String);
query.addBindValue(names);
if (!query.execBatch())
qDebug() << query.lastError();
UPDATE操作:
QSqlQuery query;
query.prepare("UPDATE employee SET salary = ? WHERE id = 1003");
query.bindValue(0, 70000);
query.exe();
DELETE操作:
QSqlQuery query;
query.exec("DELETE FROM employee WHERE id = 1007");
事务处理:
QSqlDatabase::database().transaction();
QSqlQuery query;
query.exec("SELECT id FROM employee WHERE name = 'Torild Halvorsen'");
if (query.next()) {
int employeeId = query.value(0).toInt();
query.exec("INSERT INTO project (id, name, ownerid) "
"VALUES (201, 'Manhattan Project', "
+ QString::number(employeeId) + ")");
}
QSqlDatabase::database().commit();
如果数据库引擎支持事务处理,则函数QSqlDriver::hasFeature(QSqlDriver::Transactions)将返回 真。 可以通过调用QSqlDatabase::transaction()来初始化一个事务处理。之后执行你想在该事务处理的工作。 完了再执行QSqlDatabase::commit()来提交事务处理或QSqlDatabase::rollback()取消事务处理。 这里在举个QSqlDriver::hasFeature(QSqlDriver::QuerySize)例子,可以较快的统计查询记录行数。
QSqlQuery query;
int numRows;
query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
QSqlDatabase defaultDB = QSqlDatabase::database();
if (defaultDB.driver()->hasFeature(QSqlDriver::QuerySize)) {
numRows = query.size();
} else {
// this can be very slow
query.last();
numRows = query.at() + 1;
}
存储过程: AsciiToInt()是数据库中的一个存储过程。 但我在网上以前好像看过说是SQL Server中的存储过程是通过"EXEC"完成的,而不是"CALL",这里我不确定!留下一个疑问吧~
QSqlQuery query;
query.prepare("CALL AsciiToInt(?, ?)");
query.bindValue(0, "A");
query.bindValue(1, 0, QSql::Out);
int rowNum = query.at(); //获取query所指向的记录在结果集中的编号 int columnNum = query.record().count(); //获取每条记录中属性(即列)的个数 int fieldNo = query.record().indexOf("name"); //获取"name"属性所在列的编号,列从左向右编号,最左边的编号为0 int id = query.value(0).toInt(); //获取id属性的值,并转换为int型 QString name = query.value(fieldNo).toString(); //获取name属性的值
|