qt自带的QSqlite数据库。主要掌握增删改查
常用命令
QT += sql
然后头文件
#include
#include
#include
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("127.0.0");
db.setDatabaseName(baseName); //设置数据库名称
db.setUserName("user");
db.setPassword("pwssword");
if(!db.open()){
qDebug()<<"open error:"<<db.lastError();;
}
QSqlQuery query(db);
/*id integer primary key, 这样iD 就可以自增*/
QString cmd = "create table notes(id integer primary key,
title varchar(100),
tag varchar(50),
time varchar(50),
content varchar(1000);";
if(!query.exec(cmd){
qDebug()<<"create error!";
}
QSqlQuery query(db);
/*这里id不用设置,会自增*/
QString cmd = "insert into notes(title,tag,time,content) values('QSlite test','database','2021-01-21','how to user QSlite');";
if(!query.exec(cmd){
qDebug()<<"insert error!";
}
QSqlQuery query(db);
QString cmd = "update notes set title='QSqlite test-change',
tag='QSqlite',
time='2021-01-22',
content='how to user QSlite and so on'
where id=1;";
if(!query.exec(cmd){
qDebug()<<"change error!";
}
QSqlQuery query(db);
QString cmd ="delete from notes where id=1;";
if(!query.exec(cmd){
qDebug()<<"delete error!";
}
上面是删除满足条件的数据,表结构即字段还在,可以直接再插入数据
下面是直接删除表,表名字还在,字段结构无了,必须要先create创建,才能插入数据
QSqlQuery query(db);
QString cmd ="drop table notes;";
if(!query.exec(cmd){
qDebug()<<"drop error!";
}
QSqlQuery query(db);
QString cmd ="select * from notes;"
if(!query.exec(cmd){
qDebug()<<"select error!";
}else{
while(query.next()){
qDebug()<<"id:"<<query.value(0).toString();
qDebug()<<"title:"<<query.value(1).toString();
qDebug()<<"tag:"<<query.value(2).toString();
qDebug()<<"time:"<<query.value(3).toString();
qDebug()<<"content:"<<query.value(4).toString();
}
}
上面是获取数据库中所有的数据
也可以筛选出满足条件的数据
QSqlQuery query(db);
QString cmd ="select * from notes where title='QSqlite test-change' and time='2021-01-21';"
if(!query.exec(cmd){
qDebug()<<"exec error!";
}else{
while(query.next()){
qDebug()<<"id:"<<query.value(0).toString();
qDebug()<<"title:"<<query.value(1).toString();
qDebug()<<"tag:"<<query.value(2).toString();
qDebug()<<"time:"<<query.value(3).toString();
qDebug()<<"content:"<<query.value(4).toString();
}
}
QSqlQuery query(db);
QStringList list = db.tables();
QSqlQuery query(db);
QString cmd ="PRAGMA table_info(notes);";
if(!query.exec(cmd){
qDebug()<<"exec error!";
}else{
while(query.next()){
qDebug()<<query.value(1).toString();
}
}
QSqlQuery query(db);
QString cmd ="select count() from notes;";
if(!query.exec(cmd){
qDebug()<<"exec error!";
}else{
query.seek(0);
qDebug()<<query.value(0).toInt();
}