Qt学习(十一):QT设置静态数据库
生活随笔
收集整理的這篇文章主要介紹了
Qt学习(十一):QT设置静态数据库
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
知識(shí)點(diǎn)
如果數(shù)據(jù)量少的情況下,不需要連接本地mysql,自己創(chuàng)建一個(gè)db文件就行
完整項(xiàng)目github地址:
widget.cpp
#include "widget.h" #include "ui_widget.h" #include <QSqlDatabase> #include <QDebug> #include <QMessageBox> #include <QSqlError> #include <QSqlQuery> #include <QVariantList>#define cout qDebug() << "[" << __FILE__ <<":" << __LINE__ << "]"Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget) {ui->setupUi(this);qDebug() << QSqlDatabase::drivers();//添加Sqlite數(shù)據(jù)庫(kù)QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//設(shè)置數(shù)據(jù)庫(kù)db.setDatabaseName("./info.db");//打開數(shù)據(jù)庫(kù)if( !db.open() ) //數(shù)據(jù)庫(kù)打開失敗{QMessageBox::warning(this, "錯(cuò)誤", db.lastError().text());return;}QSqlQuery query;bool ansCra=query.exec("create table student(id int primary key, name varchar(255), age int, score int);");if(!ansCra){cout<<"執(zhí)行數(shù)據(jù)庫(kù)命令出錯(cuò)";}query.prepare("insert into student(name, age, score) values(?, ?, ?)");//給字段設(shè)置內(nèi)容 listQVariantList nameList;nameList << "xiaoming" << "xiaolong" << "xiaojiang";QVariantList ageList;ageList << 11 << 22 << 33;QVariantList scoreList;scoreList << 59 << 69 << 79;//給字段綁定相應(yīng)的值 按順序綁定query.addBindValue(nameList);query.addBindValue(ageList);query.addBindValue(scoreList);//執(zhí)行預(yù)處理命令bool ansPi=query.execBatch();if(!ansPi){cout<<"執(zhí)行數(shù)據(jù)庫(kù)命令出錯(cuò)";}bool ansSel=query.exec("select * from student");if(!ansSel){cout<<"執(zhí)行數(shù)據(jù)庫(kù)命令出錯(cuò)";}while(query.next()) //一行一行遍歷{//取出當(dāng)前行的內(nèi)容qDebug() << query.value(0).toInt()<< query.value(1).toString()<< query.value("age").toInt()<< query.value("score").toInt();} }Widget::~Widget() {delete ui; }總結(jié)
以上是生活随笔為你收集整理的Qt学习(十一):QT设置静态数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt学习(十):QT连接mysql(增加
- 下一篇: ngx_lua操作Redis和Mysql