QT5.7操作SQLITE数据库

Sqlite数据可以以其小巧,不容特意安装数据库客户端和服务器,在嵌入式设备中使用广泛。QT同样也支持SQLITE数据库。

1.连接数据库

void QtGuiSqlite::sqliteInit() {
	QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "RadarState");
	db.setDatabaseName(GlobalUseInst()->loadExeDir() + "RadarState.db");
	bool b = db.open();
	if (!b) {
		qDebug() << QStringLiteral("++++++++++++++++++++++++++++++++++数据库连接失败!");
	}
}

2.插入数据

void QtGuiSqlite::slotBtnInsert() {
	QSqlDatabase db = QSqlDatabase::database("RadarState");

	QSqlQuery query(db);

	//想要插入多条数据,必须多次运行insert into语句
#if 1
	query.prepare("insert into HYMP_TEST values (:id ,:name,:age);");

	query.bindValue(":id", 1);
	query.bindValue(":name", QStringLiteral("张三"));
	query.bindValue(":age", 26);
	query.exec();
#else
	QString strSql = QString("insert into hymp_test values (2,\'李四\',45)");
	bool  b = query.exec(strSql);
#endif
	qDebug()<< query.lastError().text();
	db.commit();
}

3.删除数据

void QtGuiSqlite::slotBtnDelete() {
	QSqlDatabase db = QSqlDatabase::database("RadarState");
	QSqlQuery query(db);
	query.prepare("delete from HYMP_TEST where id = :id");
	query.bindValue(":id", 1);
	query.exec();
	db.commit();
}

4.更新数据

void QtGuiSqlite::slotBtnUpdate() {
	QSqlDatabase db = QSqlDatabase::database("RadarState");
	QSqlQuery query(db);
	query.prepare("update HYMP_TEST set name = :name , age = :age where id = :id");
	query.bindValue(":name", QStringLiteral("王五"));
	query.bindValue(":age", 89);
	query.bindValue(":id", 2);
	query.exec();
	db.commit();
}

5.查询数据

void QtGuiSqlite::slotBtnQuery() {
	QSqlDatabase db = QSqlDatabase::database("RadarState");
	QSqlQuery query2(db);
	query2.prepare("select * from HYMP_TEST a where a.id = :id");
	query2.bindValue(":id", 2);     //任务标识
	query2.exec();

	QSqlRecord rec = query2.record();

	int idxName = rec.indexOf("name");
	while (query2.next()) {
		qDebug() << query2.record().value(idxName).toString();
	}
}

你可能感兴趣的:(数据库,qt)