#include <QtGui/QApplication> #include "mainwindow.h" #include "QTextCodec" #include "QSqlDatabase" #include "QSqlQuery" #include "QVariant" #include "QString" #include "QMessageBox" int main(int argc, char *argv[]) { QApplication a(argc, argv); QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8")); QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8")); MainWindow w; w.show(); QSqlDatabase dbconn=QSqlDatabase::addDatabase("QSQLITE"); //添加数据库驱动 dbconn.setDatabaseName("mytest.db"); //在工程目录新建一个mytest.db的文件 if(!dbconn.open()) { QMessageBox::information(NULL, "err", "no db"); } QSqlQuery query;//以下执行相关QSL语句 query.exec("create table student(id varchar,name varchar)"); //新建student表,id设置为主键,还有一个name项 query.exec(QObject::tr("insert into student values(1,'第一个')")); query.exec(QObject::tr("insert into student values(2,'第二个')")); query.exec(QObject::tr("insert into student values(3,'Third')")); query.exec(QObject::tr("insert into student values(4,’Forth')")); query.exec(QObject::tr("insert into student values(5,'Fifth')")); query.exec(QObject::tr("insert into student values(6,'Sixth')")); query.exec("select id,name from student where id>=1"); while(query.next())//query.next()指向查找到的第一条记录,然后每次后移一条记录 { QString ele1=query.value(1).toString(); QMessageBox::information(NULL, query.value(0).toString(), ele1); } query.exec(QObject::tr("drop student")); return a.exec(); }