当前位置:Gxlcms > 数据库问题 > Qt之操作数据库(SQLite)实例

Qt之操作数据库(SQLite)实例

时间:2021-07-01 10:21:17 帮助过:13人阅读

<QSql> #include <QSqlDatabase> #include <QSqlError> #include <QSqlQuery> #include <QString> #include <QFile> #include <QDebug> #include <QVariantList> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE"); database.setDatabaseName("CashSystem.db"); if(database.open()) { qDebug()<<"Database Opened"; QSqlQuery sql_query; QString create_sql = "create table member (id int primary key, name varchar(30), address varchar(30))"; //创建数据表 QString insert_sql = "insert into member values(?,?,?)"; //插入数据 QString select_all_sql = "select * from member"; sql_query.prepare(create_sql); //创建表 if(!sql_query.exec()) //查看创建表是否成功 { qDebug()<<QObject::tr("Table Create failed"); qDebug()<<sql_query.lastError(); } else { qDebug()<< "Table Created" ; //插入数据 sql_query.prepare(insert_sql); QVariantList GroupIDs; GroupIDs.append(0); GroupIDs.append(1); GroupIDs.append(2); QVariantList GroupNames; GroupNames.append("hsp"); GroupNames.append("rl"); GroupNames.append("spl"); QVariantList GroupAddress; GroupAddress.append("南充"); GroupAddress.append("宝鸡"); GroupAddress.append("南充"); sql_query.addBindValue(GroupIDs); sql_query.addBindValue(GroupNames); sql_query.addBindValue(GroupAddress); if(!sql_query.execBatch()) { qDebug()<<sql_query.lastError(); } else { qDebug()<<"插入记录成功"; } //查询所有记录 sql_query.prepare(select_all_sql); if(!sql_query.exec()) { qDebug()<<sql_query.lastError(); } else { while(sql_query.next()) { int id = sql_query.value(0).toInt(); QString name = sql_query.value(1).toString(); QString address = sql_query.value(2).toString(); qDebug()<<QString("ID:%1 Name:%2 Address:%3").arg(id).arg(name).arg(address); } } } } database.close(); // QFile::remove("CashSystem.db"); return a.exec(); }

4、运行截图:

技术分享图片

5、在项目的debug文件夹下,生成了对应的.db文件,使用navicat forSqlite工具打开,显示结果如下:

技术分享图片

 

参考链接:

1、Qt之操作数据库(SQLite)实例

2、Qt---自带的数据库QSQLITE

3、在Qt中使用SQLite数据库

 

Qt之操作数据库(SQLite)实例

标签:address   ant   pos   var   .net   自适应   pre   ring   oracle   

人气教程排行