Qt SQLite简单用法

序言

感觉自己老是会忘记需要百度,干脆直接记下来

环境

Qt5.14.2 + MSVC2017(VS2019)

使用前准备

Qt Creator:

QT	+= sql

VS:

属性页-》Qt Project Settings-》Qt Modules-》Sql

.

加载SQLite

Qt自带的SQLite无账号密码可言,所以无需写

QString connectionName = QLatin1String("database");								//连接名
QSqlDatabase db;

if (QSqlDatabase::contains(connectionName))										//看是否已经连接过,有则直接连接该连接
	db = QSqlDatabase::database(connectionName);	
else {
	db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), connectionName);	//加载数据库
	db.setDatabaseName(QStringLiteral("./mosrun.db"));							//没有该文件就会自动创建
	if (!db.open()) {
		qWarning() << __FILE__ << __LINE__ << "Error" << db.lastError();		//若连接失败则打印原因
		return;
	}
}

QSqlQuery query(db);															//语句使用类

db.close();

.

SQL命令

事务

方法1:

db.transaction();
... 命令 ...
for
	query.exec("命令");
... 命令 ...
db.commit();		//提交
db.rollback();		//回滚

方法2:

query.exec(QStringLiteral("BEGIN TRANSACTION;"));
... 命令 ...
for
	query.exec("命令");
... 命令 ...
query.exec("COMMIT");//提交
query.exec("ROLLBACK");//回滚

命令

方法1

QSqlQuery query("SELECT country FROM artist");
while (query.next()) 
{
	QString country = query.value(0).toString();
	doSomething(country);
}

QSqlQuery query("SELECT * FROM artist");
int fieldNo = query.record().indexOf("country");
while (query.next()) 
{
    QString country = query.value(fieldNo).toString();
    doSomething(country);
}

方法2

QSqlQuery query("SELECT * FROM artist");
while (query.next()) 
{
    QString country = query.value("country").toString();
    doSomething(country);
}

方法3

QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
              "VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");
query.exec();

方法4

QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
              "VALUES (:id, :forename, :surname)");
query.bindValue(0, 1001);
query.bindValue(1, "Bart");
query.bindValue(2, "Simpson");
query.exec();

方法5

QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
              "VALUES (?, ?, ?)");
query.bindValue(0, 1001);
query.bindValue(1, "Bart");
query.bindValue(2, "Simpson");
query.exec();

方法6

QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
			  "VALUES (?, ?, ?)");
query.addBindValue(1001);
query.addBindValue("Bart");
query.addBindValue("Simpson");
query.exec();

方法7

QSqlQuery query;
query.prepare("CALL AsciiToInt(?, ?)");
query.bindValue(0, "A");
query.bindValue(1, 0, QSql::Out);
query.exec();
int i = query.boundValue(1).toInt(); // i is 65

未完待续…

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>