【Qt】sqlite数据库使用
生活随笔
收集整理的這篇文章主要介紹了
【Qt】sqlite数据库使用
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1、修改.pro文件,添加SQL模塊:
QT += sql2.maindow.h
#include "mainwindow.h" #include <QApplication> //添加頭文件 #include <qdebug.h> #include <QSqlDatabase> #include <QSqlError> #include <QSqlQuery>int main(int argc, char *argv[]) {QApplication a(argc, argv);//建立并打開(kāi)數(shù)據(jù)庫(kù)QSqlDatabase database;database = QSqlDatabase::addDatabase("QSQLITE");database.setDatabaseName("MyDataBase.db"); //通過(guò)QCoreApplication::applicationDirPath()獲得相對(duì)路徑/*QString PATH;PATH.append(QCoreApplication::applicationDirPath());PATH.append("/databaseUser.db");QSqlDatabase database;database = QSqlDatabase::addDatabase("QSQLITE");database.setDatabaseName(PATH);*///if (!database.open()){qDebug() << "Error: Failed to connect database." << database.lastError();}else{qDebug() << "Succeed to connect database." ;}//創(chuàng)建表格QSqlQuery sql_query;if(!sql_query.exec("create table student(id int primary key, name text, age int)")){qDebug() << "Error: Fail to create table."<< sql_query.lastError();}else{qDebug() << "Table created!";}//插入數(shù)據(jù)if(!sql_query.exec("INSERT INTO student VALUES(1, \"Wang\", 23)")){qDebug() << sql_query.lastError();}else{qDebug() << "inserted Wang!";}if(!sql_query.exec("INSERT INTO student VALUES(2, \"Li\", 23)")){qDebug() << sql_query.lastError();}else{qDebug() << "inserted Li!";}//修改數(shù)據(jù)sql_query.exec("update student set name = \"QT\" where id = 1");if(!sql_query.exec()){qDebug() << sql_query.lastError();}else{qDebug() << "updated!";}//查詢數(shù)據(jù)sql_query.exec("select * from student");if(!sql_query.exec()){qDebug()<<sql_query.lastError();}else{while(sql_query.next()){int id = sql_query.value(0).toInt();QString name = sql_query.value(1).toString();int age = sql_query.value(2).toInt();qDebug()<<QString("id:%1 name:%2 age:%3").arg(id).arg(name).arg(age);}}//刪除數(shù)據(jù)sql_query.exec("delete from student where id = 1");if(!sql_query.exec()){qDebug()<<sql_query.lastError();}else{qDebug()<<"deleted!";}//刪除表格sql_query.exec("drop table student");if(sql_query.exec()){qDebug() << sql_query.lastError();}else{qDebug() << "table cleared";}//關(guān)閉數(shù)據(jù)庫(kù)database.close();return a.exec(); }總結(jié)
以上是生活随笔為你收集整理的【Qt】sqlite数据库使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【linux】CMake Error i
- 下一篇: AI嵌入式开发:NVIDIA Jetso