首先說明參考了網路上的一個常規的代碼,但實際使用中遇到不少的問題,先把常規使用方式粘貼如下:
#include <QtCore/QCoreApplication> #include <QtSql> #include <QTextCodec> int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); QTextCodec::setCodecForTr(QTextCodec::codecForLocale()); QSqlDatabase dbconn=QSqlDatabase::addDatabase("QSQLITE"); //添加資料庫驅動 dbconn.setDatabaseName("mytest.db"); //在工程目錄建立一個mytest.db的檔案 if(!dbconn.open()) { qDebug()<<"fdsfds"; } QSqlQuery query;//以下執行相關QSL語句 query.exec("create table student(id varchar,name varchar)"); //建立student表,id設定為主鍵,還有一個name項 query.exec(QObject::tr("insert into student values(1,'aaa')")); query.exec(QObject::tr("insert into student values(2,'bbb')")); query.exec(QObject::tr("insert into student values(3,'ccc')")); query.exec(QObject::tr("insert into student values(3,'ddd')")); query.exec(QObject::tr("insert into student values(4,'eee')")); query.exec(QObject::tr("insert into student values(5,'fff')")); query.exec(QObject::tr("insert into student values(6,'ggg')")); query.exec(QObject::tr("select id,name from student where id>=1")); query.exec("select id,name from student where id>=1"); while(query.next())//query.next()指向尋找到的第一條記錄,然後每次後移一條記錄 { int ele0=query.value(0).toInt();//query.value(0)是id的值,將其轉換為int型 QString ele1=query.value(1).toString(); qDebug()<<ele0<<ele1;//輸出兩個值 } query.exec(QObject::tr("drop student")); return a.exec(); }
如上的方式不是好,只是在使用過程中有很多不便的地方,會遇到不少的問題,我會在下面的小節中修改這個思路,然後按照一般軟體開發的方式進行重新實現。