Qt QSqlTableModel判断SQLITE数据表是否存在,不存在创建数据表C++
时间: 2023-10-21 19:03:38 浏览: 242
可以使用 `QSqlQuery` 判断 SQLite 数据表是否存在,如果不存在就创建数据表。可以使用以下代码实现:
```c++
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlTableModel>
bool createTableIfNotExists(const QString &tableName, const QSqlTableModel &model) {
QSqlQuery query(model.database());
// 判断数据表是否存在
query.prepare("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=:tableName");
query.bindValue(":tableName", tableName);
if (!query.exec()) {
qDebug() << "Error occurred while checking if table exists: " << query.lastError();
return false;
}
query.next();
int count = query.value(0).toInt();
if (count == 0) {
// 数据表不存在,创建数据表
QString createTableQuery = QString("CREATE TABLE %1 (%2)").arg(tableName).arg(model.record().join(","));
if (!query.exec(createTableQuery)) {
qDebug() << "Error occurred while creating table: " << query.lastError();
return false;
}
}
return true;
}
```
其中,`tableName` 是数据表名称,`model` 是一个 `QSqlTableModel` 对象,该对象已经连接到了 SQLite 数据库并指定了数据表。在调用该函数时,只需要传入这两个参数即可。如果数据表不存在,该函数会自动创建数据表并返回 `true`,否则返回 `false`。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)