#include "widget.h" #include <QApplication> #include <QtSql> #include <QTextCodec> #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); QTextCodec::setCodecForTr(QTextCodec::codecForLocale()); /*QStringList drivers = QSqlDatabase::drivers(); //获取支持的SQL驱动 for( int i=0; i!=drivers.count(); i++ ) qDebug() << "driver: " << drivers.at(i); */ QSqlDatabase dbconn=QSqlDatabase::addDatabase("QSQLITE"); //添加数据库驱动 dbconn.setDatabaseName("mytest.db"); //在工程目录新建一个mytest.db的文件 if(!dbconn.open()) { qDebug()<<"error"; } QSqlQuery query(dbconn);//以下执行相关QSL语句 //新建student表,id设置为主键,还有一个name项 query.exec("create table student(id varchar,name varchar)"); 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,'葡萄')")); query.prepare("insert into student values(?,?)"); QVariantList ids; ids << 4 << 5 << 6; query.addBindValue(ids); QVariantList names; names << "kevin" << "xiang" << "jie"; query.addBindValue(names); if( !query.execBatch() ) qDebug() << "Error: " << query.lastError(); query.exec("update student set name='xiangjie' where id=5"); //更新 query.exec("delete from student where id=6"); //删除 //query.exec("select id,name from student where id>=2"); query.exec("select * from student"); while(query.next())//query.next()指向查找到的第一条记录,然后每次后移一条记录 { int ele0=query.value(0).toInt();//query.value(0)是id的值,将其转换为int型 QString ele1=query.value(1).toString(); qDebug()<< query.at() << ele0<<ele1;//输出两个值 } query.seek(3); QSqlRecord record = query.record(); //获取当前行记录 qDebug() << "id: " << record.value("id").toInt() << " name: " << record.value("name").toString(); QSqlField field = record.field(1); //获取索引字段 qDebug() << "field name:" << field.name() << " field value:" << field.value().toString(); query.exec(QObject::tr("drop table student")); //删除table //return a.exec(); }