有两种方法,一种使用qt中的QSqlDatabase模块,另一种使用sqlite3提供的c/c++接口。
其中第一种需要需要在工程下的.pro文件中加入“QT += sql”,在qt安装目录对应的编译器下的plugins目录中要有sqldrivers文件夹
第二种方法需要在sqlite官网(https://www.sqlite.org/download.html)下载源码,将其中的头文件和cpp文件加入当前工程
两种方法代码如下:
//方法一:QT数据库模块
void DB_Operate(){
QSqlDatabase m_db;
//加载数据库驱动
m_db = QSqlDatabase::addDatabase("QSQLITE");
//指定数据库文件路径
m_db.setDatabaseName("backuplist.db");
//打开数据库
if(!m_db.open())
{
qDebug()<< "open db failed";
m_db.close();
}
QSqlQuery *query = new QSqlQuery();
QString commandLine = "create table if not exists DriversBackup(DeviceName,BackupName,BackupDateTime)";
query->exec(commandLine);
commandLine = "insert into DriversBackup(DeviceName,BackupName,BackupDateTime) values('desc','driver','" + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") + "')";
if(!query->exec(commandLine)){
qDebug()<< "insert data failed";
}
commandLine = "select * from DriversBackup";
if(!query->exec(commandLine)){
qDebug()<< "select data failed";
}else{
while(query->next()){
qDebug()<< query->value("BackupName").toString();
qDebug()<< query->value("DeviceName").toString();
qDebug()<< query->value("BackupDateTime").toString();
}
}
m_db.close();
}
//方法二:sqlite3 c/c++接口
static int callback(void *data, int argc, char **argv, char **azColName){
QString strRec(argv[0]);
QStringList text = strRec.split(" ");
foreach (QString txt, text) {
if (txt.length() > 0) {
qDebug()<< txt;
}
return 0;
}
}
void DB_Operate(int)
{
sqlite3 *db;
int ret = sqlite3_open("tmp.db",&db);
if(ret != SQLITE_OK){
sqlite3_close(db);
return;
}
QString commandLine = "create table if not exists DriversBackup(DeviceName,BackupName,BackupDateTime)";
char *msg = 0;
ret = sqlite3_exec(db, commandLine.toStdString().c_str(), callback, 0, &msg);
if(ret != SQLITE_OK){
sqlite3_free(msg);
sqlite3_close(db);
return;
}
commandLine = "insert into DriversBackup(DeviceName,BackupName,BackupDateTime) values('desc','driver','" + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") + "')";
ret = sqlite3_exec(db, commandLine.toStdString().c_str(), callback, 0, &msg);
if(ret != SQLITE_OK){
sqlite3_free(msg);
sqlite3_close(db);
return;
}
commandLine = "select * from DriversBackup";
ret = sqlite3_exec(db, commandLine.toStdString().c_str(), callback, 0, &msg);
sqlite3_free(msg);
sqlite3_close(db);
}