QT中简单使用SQLITE数据库

前端之家收集整理的这篇文章主要介绍了QT中简单使用SQLITE数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
QT中简单使用SQLITE数据库

代码:mian.cpp

  1. #include<QtCore/QCoreApplication>
  2. #include<Qtsql>
  3. #include<QDebug>
  4. intmain(intargc,char*argv[])
  5. {
  6. QCoreApplicationa(argc,argv);
  7. QsqlDatabasedb=QsqlDatabase::addDatabase("QsqlITE");
  8. db.setDatabaseName("/tmp/my.db");
  9. if(!db.open())
  10. {
  11. qDebug()<<"opendatabaseFailed---"<<db.lastError().text()<<"/n";
  12. return-1;
  13. }
  14. QsqlQueryquery;
  15. boolok=query.exec("CREATETABLEIFNOTEXISTSpeople(idINTEGERPRIMARYKEYAUTOINCREMENT,"
  16. "nameVARCHAR(20)NOTNULL,"
  17. "ageINTEGERNULL)");
  18. if(ok)
  19. qDebug()<<"ceatetablepartitionsuccess/n";
  20. else
  21. qDebug()<<"ceatetablepartitionFailed/n";
  22. for(inti=0;i<3;++i)
  23. query.prepare("INSERTINTOpeople(id,name,age)VALUES(:id,:name,:age)");
  24. query.bindValue(":name",QString("smith_%1").arg(i+1));
  25. query.bindValue(":age",20+i*5);
  26. query.exec();
  27. }
  28. //QsqlQueryquery;
  29. query.exec("SELECTid,ageFROMpeople");
  30. while(query.next())
  31. qDebug()<<"people("<<query.value(0).toInt()<<")name:"<<query.value(1).toString()<<"age:"<<query.value(2).toInt();
  32. returna.exec();
  33. }

sql.pro:

?@H_361_301@
    QT+=coresql
  1. QT-=gui
  2. TARGET=sql
  3. CONFIG+=console
  4. CONFIG-=app_bundle
  5. LIBS+=-lsqlite3
  6. TEMPLATE=app
  7. SOURCES+=main.cpp

编译运行,输出

ceate table partition success

people( 1 ) name: "smith_1" age: 20

people( 2 ) name: "smith_2" age: 25

people( 3 ) name: "smith_3" age: 30

猜你在找的Sqlite相关文章