13,005
回編集
79行目: | 79行目: | ||
#include <QtSql> | #include <QtSql> | ||
#include <QString> | |||
#include <QSqlError> | |||
#include <stdexcept> | |||
#include <QDebug> | #include <QDebug> | ||
class DatabaseException : public std::runtime_error | |||
{ | |||
public: | |||
DatabaseException(const QString& message) : std::runtime_error(message.toStdString()) {} | |||
}; | |||
class DatabaseManager | class DatabaseManager | ||
93行目: | 102行目: | ||
bool updateRecord(int id, const QString &name, int age); | bool updateRecord(int id, const QString &name, int age); | ||
bool deleteRecord(int id); | bool deleteRecord(int id); | ||
QList<QMap<QString, QVariant>> readAllRecords(); | |||
private: | private: | ||
QSqlDatabase db; | QSqlDatabase db; | ||
void checkConnection(); | |||
void handleDatabaseError(const QString &operation, const QSqlError &error); | |||
}; | }; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
123行目: | 134行目: | ||
{ | { | ||
if (!db.open()) { | if (!db.open()) { | ||
throw DatabaseException("Failed to open database connection: " + db.lastError().text()); | |||
} | } | ||
qDebug() << "Database connection opened successfully"; | |||
} | } | ||
135行目: | 143行目: | ||
void DatabaseManager::closeConnection() | void DatabaseManager::closeConnection() | ||
{ | { | ||
db.close(); | if (db.isOpen()) { | ||
db.close(); | |||
qDebug() << "Database connection closed"; | |||
} | |||
} | |||
// 接続の確認 | |||
void DatabaseManager::checkConnection() | |||
{ | |||
if (!db.isOpen()) { | |||
throw DatabaseException("Database connection is not open"); | |||
} | |||
} | |||
// エラーハンドリング処理 | |||
void DatabaseManager::handleDatabaseError(const QString &operation, const QSqlError &error) | |||
{ | |||
QString errorMessage = QString("%1 failed: %2").arg(operation, error.text()); | |||
throw DatabaseException(errorMessage); | |||
} | } | ||
141行目: | 167行目: | ||
bool DatabaseManager::createTable() | bool DatabaseManager::createTable() | ||
{ | { | ||
checkConnection(); | |||
QSqlQuery query; | QSqlQuery query; | ||
query. | if (!query.exec("CREATE TABLE IF NOT EXISTS people (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(40) NOT NULL, age INT)")) { | ||
handleDatabaseError("Create table", query.lastError()); | |||
} | } | ||
qDebug() << "Table 'people' created or already exists"; | |||
} | } | ||
155行目: | 180行目: | ||
bool DatabaseManager::insertRecord(const QString& name, int age) | bool DatabaseManager::insertRecord(const QString& name, int age) | ||
{ | { | ||
checkConnection(); | |||
QSqlQuery query; | QSqlQuery query; | ||
query.prepare("INSERT INTO people (name, age) VALUES (:name, :age)"); | query.prepare("INSERT INTO people (name, age) VALUES (:name, :age)"); | ||
161行目: | 188行目: | ||
if (!query.exec()) { | if (!query.exec()) { | ||
handleDatabaseError("Insert record", query.lastError()); | |||
} | } | ||
qDebug() << "Record inserted successfully"; | |||
} | } | ||
171行目: | 197行目: | ||
bool DatabaseManager::updateRecord(int id, const QString& name, int age) | bool DatabaseManager::updateRecord(int id, const QString& name, int age) | ||
{ | { | ||
checkConnection(); | |||
QSqlQuery query; | QSqlQuery query; | ||
query.prepare("UPDATE people SET name = :name, age = :age WHERE id = :id"); | query.prepare("UPDATE people SET name = :name, age = :age WHERE id = :id"); | ||
178行目: | 206行目: | ||
if (!query.exec()) { | if (!query.exec()) { | ||
handleDatabaseError("Update record", query.lastError()); | |||
} | } | ||
if (query.numRowsAffected() == 0) { | |||
throw DatabaseException(QString("No record found with id: %1").arg(id)); | |||
} | |||
qDebug() << "Record updated successfully"; | |||
} | } | ||
// レコードの削除 | |||
bool DatabaseManager::deleteRecord(int id) | bool DatabaseManager::deleteRecord(int id) | ||
{ | { | ||
checkConnection(); | |||
QSqlQuery query; | QSqlQuery query; | ||
query.prepare("DELETE FROM people WHERE id = :id"); | query.prepare("DELETE FROM people WHERE id = :id"); | ||
query.bindValue(":id", id); | query.bindValue(":id", id); | ||
if (!query.exec()) { | |||
handleDatabaseError("Delete record", query.lastError()); | |||
} | |||
if ( | if (query.numRowsAffected() == 0) { | ||
throw DatabaseException(QString("No record found with id: %1").arg(id)); | |||
} | } | ||
qDebug() << "Record deleted successfully"; | |||
} | } | ||
// 全てのレコードを読み込む | // 全てのレコードを読み込む | ||
QList<QMap<QString, QVariant>> DatabaseManager::readAllRecords() | |||
{ | { | ||
checkConnection(); | |||
QSqlQuery query("SELECT * FROM people"); | QSqlQuery query("SELECT * FROM people"); | ||
QList<QMap<QString, QVariant>> results; | |||
if (!query.exec()) { | |||
handleDatabaseError("Read all records", query.lastError()); | |||
} | |||
while (query.next()) { | while (query.next()) { | ||
QMap<QString, QVariant> record; | |||
record["id"] = query.value(0); | |||
record["name"] = query.value(1); | |||
record["age"] = query.value(2); | |||
results.append(record); | |||
} | } | ||
return results; | |||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
219行目: | 267行目: | ||
DatabaseManager dbManager; | DatabaseManager dbManager; | ||
try { | |||
// データーベースの接続 | |||
dbManager.openConnection(); | |||
// テーブルの作成 | // テーブルの作成 | ||
dbManager.createTable(); | dbManager.createTable(); | ||
228行目: | 279行目: | ||
// 全てのレコードを読み込む | // 全てのレコードを読み込む | ||
dbManager.readAllRecords(); | QList<QMap<QString, QVariant>> records = dbManager.readAllRecords(); | ||
for (const auto& record : records) { | |||
qDebug() << "ID:" << record["id"].toInt() | |||
<< "Name:" << record["name"].toString() | |||
<< "Age:" << record["age"].toInt(); | |||
} | |||
// 既存のレコードの更新 | |||
dbManager.updateRecord(1, "John Doe Updated", 31); | |||
// 任意のレコードの削除 | |||
dbManager.deleteRecord(2); | |||
// 全てのレコードを読み込む | |||
records = dbManager.readAllRecords(); | |||
for (const auto& record : records) { | |||
// | qDebug() << "ID:" << record["id"].toInt() | ||
<< "Name:" << record["name"].toString() | |||
<< "Age:" << record["age"].toInt(); | |||
} | |||
} | |||
catch (const DatabaseException &e) { | |||
// データベース関連のエラー | |||
qCritical() << "Database error: " << e.what(); | |||
} | |||
catch (const std::exception &e) { | |||
// その他のエラー | |||
qCritical() << "Unexpected error: " << e.what(); | |||
} | } | ||