1. 程式人生 > 實用技巧 >Qt-資料庫操作SQLite

Qt-資料庫操作SQLite

1 簡介

參考視訊:https://www.bilibili.com/video/BV1XW411x7NU?p=88

說明:本文對在Qt中操作SQLite做簡要說明。

SQLite:SQLite 是一個軟體庫,實現了自給自足的、無伺服器的、零配置的、事務性的 SQL 資料庫引擎。具體的操作命令可參考:https://www.runoob.com/sqlite/sqlite-tutorial.html

在Qt中操作SQLite不需要我們單獨先安裝它,可以直接使用。

2 測試及說明

語法就不介紹了,這裡說明功能:建立一個info.db資料庫,插入一些資料,然後遍歷輸出。

程式碼步驟說明:

(1)新增sqlite資料庫

 db = QSqlDatabase::addDatabase("QSQLITE");

(2)建立資料庫

語法和之前操作MySql一樣:

 QSqlQuery query;
query.exec("create table student(id int primary key, name varchar(255), age int, score int);");

(3)批量插入條目

     //批量插入:odbc風格
//預處理語句
query.prepare("insert into student(name, age, score) values(?, ?, ?);");
// 給欄位設定內容
QVariantList nameList;
nameList << "xiaoming" << "xiaokong" << "xiaojiang";
QVariantList ageList;
ageList << << << ;
QVariantList scoreList;
scoreList << << << ;
//給欄位繫結相應的值,必須按順序繫結
query.addBindValue(nameList);
query.addBindValue(ageList);
query.addBindValue(scoreList);
//執行預處理命令
query.execBatch();

(4)遍歷輸出

     query.exec("select * from student");
while (true == query.next()) { //一行一行遍歷
//取出當前行的內容,以列為單位
qDebug() << query.value().toInt() //取第一列
<< query.value().toString() //取第二列
<< query.value("age").toInt()
<< query.value("score").toInt();
}

完整程式碼:

 #include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlQuery> Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this); //列印qt支援的資料庫驅動
qDebug() << QSqlDatabase::drivers(); //新增sqlite資料庫
db = QSqlDatabase::addDatabase("QSQLITE");
//設定資料庫
db.setDatabaseName("../info.db");
//開啟資料庫
if (db.open() == false) {
QMessageBox::warning(this, "錯誤", db.lastError().text());
return;
}
//操作sql語句
QSqlQuery query;
query.exec("create table student(id int primary key, name varchar(255), age int, score int);");
//批量插入:odbc風格
//預處理語句
query.prepare("insert into student(name, age, score) values(?, ?, ?);");
// 給欄位設定內容
QVariantList nameList;
nameList << "xiaoming" << "xiaokong" << "xiaojiang";
QVariantList ageList;
ageList << << << ;
QVariantList scoreList;
scoreList << << << ;
//給欄位繫結相應的值,必須按順序繫結
query.addBindValue(nameList);
query.addBindValue(ageList);
query.addBindValue(scoreList);
//執行預處理命令
query.execBatch(); query.exec("select * from student");
while (true == query.next()) { //一行一行遍歷
//取出當前行的內容,以列為單位
qDebug() << query.value().toInt() //取第一列
<< query.value().toString() //取第二列
<< query.value("age").toInt()
<< query.value("score").toInt();
}
} Widget::~Widget()
{
delete ui;
}