Qt可以使用QSqlDatabase类连接和操作数据库。导入SQL文件的一种方法是将其读入字符串,然后使用该字符串执行SQL语句。
以下是一个示例代码:
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QSqlQuery>
// 执行 SQL 文件
bool executeSqlFile(QSqlDatabase db, const QString &filePath)
{
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qWarning() << "Failed to open SQL file: " << filePath;
return false;
}
QTextStream in(&file);
in.setCodec("UTF-8");
QStringList queries = in.readAll().split(';', QString::SkipEmptyParts);
for (QString query : queries) {
QSqlQuery q(db);
if (!q.exec(query.trimmed())) {
qWarning() << "Failed to execute query: " << q.lastError();
return false;
}
}
return true;
}
该函数从文件中读取SQL语句,并将其分割为单独的查询。然后,它使用QSqlQuery类在数据库中执行每个查询。如果任何查询失败,则返回false。
领Qt资料→「链接」
您可以按以下方式调用此函数:
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setUserName("root");
db.setPassword("password");
db.setDatabaseName("database_name");
if (!db.open()) {
// 处理连接错误
}
if (!executeSqlFile(db, "/path/to/sql/file.sql")) {
// 处理 SQL 错误
}
此代码假定您已经正确设置了数据库连接参数。执行SQL文件时,请确保指定正确的文件路径。