Qt学习(十一):QT设置静态数据库
生活随笔
收集整理的這篇文章主要介紹了
Qt学习(十一):QT设置静态数据库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
知識點
如果數據量少的情況下,不需要連接本地mysql,自己創建一個db文件就行
完整項目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數據庫QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//設置數據庫db.setDatabaseName("./info.db");//打開數據庫if( !db.open() ) //數據庫打開失敗{QMessageBox::warning(this, "錯誤", 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<<"執行數據庫命令出錯";}query.prepare("insert into student(name, age, score) values(?, ?, ?)");//給字段設置內容 listQVariantList nameList;nameList << "xiaoming" << "xiaolong" << "xiaojiang";QVariantList ageList;ageList << 11 << 22 << 33;QVariantList scoreList;scoreList << 59 << 69 << 79;//給字段綁定相應的值 按順序綁定query.addBindValue(nameList);query.addBindValue(ageList);query.addBindValue(scoreList);//執行預處理命令bool ansPi=query.execBatch();if(!ansPi){cout<<"執行數據庫命令出錯";}bool ansSel=query.exec("select * from student");if(!ansSel){cout<<"執行數據庫命令出錯";}while(query.next()) //一行一行遍歷{//取出當前行的內容qDebug() << query.value(0).toInt()<< query.value(1).toString()<< query.value("age").toInt()<< query.value("score").toInt();} }Widget::~Widget() {delete ui; }總結
以上是生活随笔為你收集整理的Qt学习(十一):QT设置静态数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt学习(十):QT连接mysql(增加
- 下一篇: javascript解析json格式的字