项目中需要用到小型数据库,查了一下Qt支持QMYSQL、QSQLITE等很多类型的数据库,使用MySQL需要安装一些相关软件或编译相关开发库,故选择QSQLITE数据库。
创建数据库及数据库表格可使用软件手动创建编辑,也可使用程序创建、操作。测试程序代码如下所示:
//main.cpp
#include
#include
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "test.db" );
if( !db.open() )
return false;
QSqlQuery query;
query.exec( "CREATE TABLE student("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"name VARCHAR,"
"age INT)" );
query.exec( "insert into student values( 0, 'LL', 16 )" );
query.exec( "insert into student values( 1, 'MM', 17 )" );
query.exec( "insert into student values( 2, 'NN', 18 )" );
query.exec( "select * from student" );
while( query.isActive() && query.next() )
{
qDebug() << query.value( 0 ).toInt() << query.value( 1 ).toString()
<< query.value( 2 ).toInt() << "\n";
}
return a.exec();
}
结果: