加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

QT 操作SQLITE3 数据库

发布时间:2020-12-12 19:28:15 所属栏目:百科 来源:网络整理
导读:QtSql模块提供了与平台以及数据库种类无关的访问SQL数据库的接口,这个接口由利用Qt的模型视图结构将数据库与用户界面集成的一套类来支持。 QSqlDatabase对象象征了数据库的关联。Qt使用驱动程序与各种数据库的应用编程接口进行通信。Qt的桌面版(Desktop Ed

QtSql模块提供了与平台以及数据库种类无关的访问SQL数据库的接口,这个接口由利用Qt的模型视图结构将数据库与用户界面集成的一套类来支持。
QSqlDatabase对象象征了数据库的关联。Qt使用驱动程序与各种数据库的应用编程接口进行通信。Qt的桌面版(Desktop Edition)包括如下一些驱动程序:

驱动程序 数据库
QDB2 IBM DB2 7.1版以及更新的版本
QIBASE Borland InterBase
QMYSQL MySql
QOCI 甲骨文公司(Oracle Call Interface)
QODBCODBC(包括微软公司的QSL服务)
QPSQLPostgreSQL的7.3版以及更高版本
QSQLITE QSLite第3版
QSQLITE2 QSLite第2版

QTDSQybase自适应服务器


访问QSqlite数据库的实例:

步骤:

1、创建Qt控制台程序。

2、在pro问价中添加QT +=sql;

3、在main.cpp中添加如下代码:


[cpp]view plaincopyprint?

在CODE上查看代码片

派生到我的代码片

  1. #include<QCoreApplication>

  2. #include<QSql>

  3. #include<QSqlDatabase>

  4. #include<QSqlError>

  5. #include<QSqlQuery>

  6. #include<QString>

  7. #include<QFile>

  8. #include<QDebug>

  9. #include<QVariantList>

  10. intmain(intargc,char*argv[])

  11. {

  12. QCoreApplicationa(argc,argv);

  13. QSqlDatabasedatabase=QSqlDatabase::addDatabase("QSQLITE");

  14. database.setDatabaseName("CashSystem.db");

  15. if(database.open())

  16. qDebug()<<"DatabaSEOpened";

  17. QSqlQuerysql_query;

  18. QStringcreate_sql="createtablemember(idintprimarykey,namevarchar(30),addressvarchar(30))";//创建数据表

  19. QStringinsert_sql="insertintomembervalues(?,?,?)";//插入数据

  20. QStringselect_all_sql="select*frommember";

  21. sql_query.prepare(create_sql);//创建表

  22. if(!sql_query.exec())//查看创建表是否成功

  23. qDebug()<<QObject::tr("TableCreatefailed");

  24. qDebug()<<sql_query.lastError();

  25. }

  26. else

  27. "TableCreated";

  28. sql_query.prepare(insert_sql);

  29. QVariantListGroupIDs;

  30. GroupIDs.append(0);

  31. GroupIDs.append(1);

  32. GroupIDs.append(2);

  33. QVariantListGroupNames;

  34. GroupNames.append("hsp");

  35. "rl");

  36. "spl");

  37. QVariantListGroupAddress;

  38. GroupAddress.append("南充");

  39. "宝鸡");

  40. sql_query.addBindValue(GroupIDs);

  41. sql_query.addBindValue(GroupNames);

  42. sql_query.addBindValue(GroupAddress);

  43. if(!sql_query.execBatch())

  44. "插入记录成功";

  45. //查询所有记录

  46. sql_query.prepare(select_all_sql);

  47. if(!sql_query.exec())

  48. while(sql_query.next())

  49. intid=sql_query.value(0).toInt();

  50. QStringname=sql_query.value(1).toString();

  51. QStringaddress=sql_query.value(2).toString();

  52. qDebug()<<QString("ID:%1Name:%2Address:%3").arg(id).arg(name).arg(address);

  53. database.close();

  54. //QFile::remove("CashSystem.db");

  55. returna.exec();

  56. }



4、运行截图:



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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读