首先要在.pro文件中加入sql
QT += core gui sql
引入頭文件
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
建立並打開數據庫
QSqlDatabase database;
database = QSqlDatabase::addDatabase("QSQLITE"); //添加數據庫名稱,這裏寫QSQLITE
database.setDatabaseName("MyDataBase.db"); //這裏寫數據庫文件名
if (!database.open())
{
qDebug() << "Error: Failed to connect database." << database.lastError();
}
else
{
qDebug() << "Succeed to connect database." ;
}
創建表
QSqlQuery sql_query;
if(!sql_query.exec("create table allfilesdata( \
fileid INTEGER primary key AUTOINCREMENT, \
filename text UNIQUE, \
filepath text NOT NULL, \
filesize INTEGER, \
fileattributes INTEGER NOT NULL, \
creat_dwlowtime INTEGER NOT NULL, \
creat_dwhightime INTEGER NOT NULL, \
lastaccess_dwlowtime INTEGER NOT NULL, \
lastaccess_dwhightime INTEGER NOT NULL, \
lastwrite_dwlowtime INTEGER NOT NULL, \
lastwrite_dwhightime INTEGER NOT NULL)"))
{
qDebug() << "Error: Fail to create table."<< sql_query.lastError();
}
else
{
qDebug() << "Table created!";
}
插入數據
QSqlQuery sql_query;
sql_query.prepare("INSERT INTO allfilesdata(filename,filepath,filesize,fileattributes,creat_dwlowtime,creat_dwhightime,lastaccess_dwlowtime,lastaccess_dwhightime,lastwrite_dwlowtime,lastwrite_dwhightime) VALUES(:filename,:filepath,:filesize,:fileattributes,:creat_dwlowtime,:creat_dwhightime,:lastaccess_dwlowtime,:lastaccess_dwhightime,:lastwrite_dwlowtime,:lastwrite_dwhightime)");
sql_query.bindValue(":filename",QString::fromStdWString(fd.cFileName));
sql_query.bindValue(":filepath",QString::fromStdWString(folder));
sql_query.bindValue(":filesize",(int)(fd.nFileSizeHigh*(MAXDWORD + 1) + fd.nFileSizeLow));
sql_query.bindValue(":fileattributes",(int)fd.dwFileAttributes);
sql_query.bindValue(":creat_dwlowtime",(int)fd.ftCreationTime.dwLowDateTime);
sql_query.bindValue(":creat_dwhightime",(int)fd.ftCreationTime.dwHighDateTime);
sql_query.bindValue(":lastaccess_dwlowtime",(int)fd.ftLastAccessTime.dwLowDateTime);
sql_query.bindValue(":lastaccess_dwhightime",(int)fd.ftLastAccessTime.dwHighDateTime);
sql_query.bindValue(":lastwrite_dwlowtime",(int)fd.ftLastWriteTime.dwLowDateTime);
sql_query.bindValue(":lastwrite_dwhightime",(int)fd.ftLastWriteTime.dwHighDateTime);
if(!sql_query.exec())
{
qDebug() << sql_query.lastError();
}
else
{
qDebug() << "inserted data successfully!";
}
佔位符
QSqlQuery sql_query;
QString searchstr="select * from allfilesdata where filename LIKE :linetext";
sql_query.prepare(searchstr);
sql_query.bindValue(":linetext",QString("%%1%").arg(linetext));
注意,LIKE子句中使用到的百分號(%)不是在SQL字符串中出現的,而是在綁定佔位符的值的時候出現的,而且LIKE子句在SQL字符串中不能使用單引號(’),因爲佔位符的類型就是字符串,所以就不需要在LIKE子句中再使用單引號(’)了
轉義字符
sqlite裏的單引號轉義不是用反斜槓’/‘而是用單引號,就是在單引號前再加一個單引號(’’)