Qt5连接sqlite数据库

本文详细介绍如何在Qt中配置和使用SQLite数据库,包括数据库连接、表创建、数据插入及查询等关键步骤,并提供实际代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先要在.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里的单引号转义不是用反斜杠’/‘而是用单引号,就是在单引号前再加一个单引号(’’)

Qt连接SQLite数据库是一个常见的需求,Qt提供了强大的数据库支持,使得连接SQLite数据库变得相对简单。以下是具体步骤: 1. **引入必要的模块**:在Qt项目中,需要引入`QtSql`模块。可以在`.pro`文件中添加以下行: ```plaintext QT += sql ``` 2. **包含头文件**:在需要连接数据库的源文件中,包含`QSqlDatabase`头文件。 ```cpp #include <QSqlDatabase> ``` 3. **添加数据库驱动**:使用`QSqlDatabase`类添加SQLite数据库驱动。 ```cpp QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); ``` 4. **设置数据库名称**:设置SQLite数据库文件的名称。如果文件不存在,SQLite会自动创建一个新的数据库文件。 ```cpp db.setDatabaseName("my_database.db"); ``` 5. **打开数据库**:尝试打开数据库连接。 ```cpp if (!db.open()) { qDebug() << "无法连接数据库"; return; } ``` 6. **执行SQL语句**:使用`QSqlQuery`类执行SQL语句。 ```cpp QSqlQuery query; query.exec("CREATE TABLE IF NOT EXISTS person (id INTEGER PRIMARY KEY, name TEXT)"); query.exec("INSERT INTO person (name) VALUES ('John Doe')"); ``` 7. **查询数据**:使用`QSqlQuery`类查询数据。 ```cpp QSqlQuery query("SELECT * FROM person"); while (query.next()) { int id = query.value(0).toInt(); QString name = query.value(1).toString(); qDebug() << "ID:" << id << "Name:" << name; } ``` 8. **关闭数据库连接**:操作完成后,关闭数据库连接。 ```cpp db.close(); ``` 通过以上步骤,你可以在Qt中成功连接并操作SQLite数据库
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值