环境:DebianGNU/Linux8.1
QT版本:Qt Creator 3.2.1 Based on Qt 5.3.2(GCC 4.9.2,32bit)
QT += sql
头文件
#include<Qtsql>
(1)建数据库、建表、插入数据、读取数据
QsqlDatabase db = QsqlDatabase::addDatabase("QsqlITE"); db.setDatabaseName("DB.db"); if(!db.open()) { qDebug() << "database open Failed!"; return ; } QsqlQuery query; query.exec("create table student(id varchar,name varchar)"); query.exec(QObject::tr("insert into student values(1,'Rachel')")); query.exec(QObject::tr("insert into student values(2,'Phoebe')")); query.exec(QObject::tr("insert into student values(3,'Monica')")); query.exec(QObject::tr("insert into student values(4,'Chandler')")); query.exec(QObject::tr("insert into student values(5,'张三')")); query.exec(QObject::tr("insert into student values(6,'李四')")); query.exec(QObject::tr("insert into student values(7,'王五')")); query.exec(QObject::tr("insert into student values(8,'赵四')")); query.exec(QObject::tr("insert into student values(9,'赵五')")); query.exec(QObject::tr("insert into student values(10,'赵六')")); query.exec("select id,name from student where id>=1"); while(query.next()) { int ele0=query.value(0).toInt(); QString ele1 = query.value(1).toString(); qDebug() << ele0 << " " << ele1; }
(2)建数据库、建表(主键自增)、插入数据、读取数据
QsqlDatabase db = QsqlDatabase::addDatabase("QsqlITE"); db.setDatabaseName("DB.db"); if(!db.open()) { qDebug() << "database open Failed!"; return ; } QsqlQuery query; query.exec("create table student(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL)"); query.exec(QObject::tr("insert into student values(NULL,'Rachel')")); query.exec(QObject::tr("insert into student values(NULL,'Phoebe')")); query.exec(QObject::tr("insert into student values(NULL,'Monica')")); query.exec(QObject::tr("insert into student values(NULL,'Chandler')")); query.exec(QObject::tr("insert into student values(NULL,'张三')")); query.exec(QObject::tr("insert into student values(NULL,'李四')")); query.exec(QObject::tr("insert into student values(NULL,'王五')")); query.exec(QObject::tr("insert into student values(NULL,'赵四')")); query.exec(QObject::tr("insert into student values(NULL,'赵五')")); query.exec(QObject::tr("insert into student values(NULL,name from student where id>=1"); while(query.next()) { int ele0=query.value(0).toInt(); QString ele1 = query.value(1).toString(); qDebug() << ele0 << " " << ele1; }原文链接:https://www.f2er.com/sqlite/198828.html