//本文描述了QT Sqlite 内存模式 ,使用QT 自带库文件,写入和读取。
//QT 6.2.4 MSVC2019调试通过。
//需要在pro文件中加入QT += sql
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlDriver>
//#include <QSqlError>
//#include <QStringList>
//#include <QVariant>
static bool createConnection()
{
//addDatabase的原型是
//QSqlDatabase::addDatabase
// (const QString &type,/*类型*/
// const QString &connectionName = QLatin1String(defaultConnection))//连接名称
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if(!db.open())
{
qDebug()<<"sqlite memory db is not open";
return false;
}
QSqlQuery query;
query.exec("create table student(id int primary key,name vachar(20))");//
query.exec("insert into student values(0,'Jack_Ma')");
query.exec("insert into student values(1,'HuaTeng_Ma')");
query.exec("insert into student values(2,'QiangDong_Liu')");
query.exec("insert into student values(3,'YanHong_Li')");
query.exec("insert into student values(4,'Lei_Ding')");
return true;
}
int main(int argc,char* argv[])
{
QCoreApplication a(argc, argv);
qDebug()<<"Available drivers:";
QStringList dataDrivers = QSqlDatabase::drivers();
for(auto item:dataDrivers)
{
qDebug()<<item;
}
if(!createConnection())
return 1;
QSqlQuery query;
query.exec("select * from student");
qDebug()<<"all records:";
while(query.next())
{
qDebug()<<query.value(0).toInt()<<query.value(1).toString();//逐行打印各记录
}
query.exec("select count (*) from student");
qDebug()<<"records count number:";
while(query.next())
{
qDebug()<<query.value(0).toInt();//打印记录数
}
return a.exec();
}