Qt筆記——QSqlLite
阿新 • • 發佈:2018-04-15
ren pri while prim bind student wid sts OS
靜態數據庫,簡單方便
在.pro文件裏添加 +sql
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget *ui; }; #endif // WIDGET_H
#include "widget.h" #include "ui_widget.h" #include <QSqlDatabase> #include <QDebug> #include <QMessageBox> #include <QSqlError> #include <QSqlQuery> #include <QVariantList> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this);//打印Qt支持的數據庫驅動 qDebug()<<QSqlDatabase::drivers(); //添加Sqlite數據庫 QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); //設置數據庫 db.setDatabaseName("../info.db"); //打開數據庫 if(!db.open()) { QMessageBox::warning(this,"error",db.lastError().text()); return; } QSqlQuery query; query.exec("create table if not exists student(id int primary key, name varchar(255), age int, score int)"); query.prepare("insert into student(id,name, age, score) values(:id,:name, :age, :score)"); //給字段設置內容 list QVariantList idList; idList<<1<<2<<3; QVariantList nameList; nameList << "xiaoming" << "xiaolong" << "xiaojiang"; QVariantList ageList; ageList << 11 << 22 <<33; QVariantList scoreList; scoreList << 59 << 69 << 70; //給字段綁定相應的值 按順序綁定 query.addBindValue(idList); query.addBindValue(nameList); query.addBindValue(ageList); query.addBindValue(scoreList); //執行預處理命令 query.execBatch(); query.exec("select * from student"); 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筆記——QSqlLite