General and Desktop
2019.01.23 22:08

Qt SQL을 이용한 가벼운 데이터베이스 다루기

조회 수 9508 추천 수 0 댓글 1
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

SQLite는 MySQL나 PostgreSQL와 같은 데이터베이스 관리 시스템이지만, 서버가 아니라 응용 프로그램에 넣어 사용하는 비교적 가벼운 데이터베이스이다. Qt SQL을 이용해서 가벼운 데이터베이스를 다루어보자.

 

가장 먼저 프로젝트 파일에 다음과 같이 명시한다.

QT += sql

 

소스파일에는 다음과 같이 추가한다.

#include <QtSql>

 

이제 프로젝트에서 Qt SQL 클래스들을 사용할 수 있다. http://doc.qt.io/qt-5/qtsql-module.html

 

아래는 데이터베이스를 핸들링하는 간단한 예제이다.

 

sqldatabase.h

#include <QObject>
#include <QtSql>

class SQLDatabase: public QObject
{
    Q_OBJECT
public:
    SQLDatabase(QObject *parent = nullptr);

    QSqlError addConnection(const QString &driver, const QString &dbName, const QString &name);

    void exec(const QString& q);

    void exec(const QString& q, QVariantList& data);

private:
    QString activeDb;
};

 

sqldatabase.cpp

#include "sqldatabase.h"

SQLDatabase::SQLDatabase(QObject *parent)
    :QObject (parent)
{
    if (QSqlDatabase::drivers().isEmpty())
        qDebug() << "No database drivers found This demo requires at least one Qt database driver. "
                    "Please check the documentation how to build the "
                    "Qt SQL plugins.";
}

QSqlError SQLDatabase::addConnection(const QString &driver, const QString &dbName, const QString &name)
{
    QSqlError err;
    QSqlDatabase db = QSqlDatabase::addDatabase(driver, QString("%1").arg(name));
    db.setDatabaseName(dbName);

    if (!db.open()) {
        err = db.lastError();
        db = QSqlDatabase();
        QSqlDatabase::removeDatabase(QString("%1").arg(name));
    }

    activeDb = name;

    return err;
}

void SQLDatabase::exec(const QString &q)
{
    QSqlQuery query(QSqlDatabase::database(activeDb));
    query.prepare(q);
    query.exec();
}

void SQLDatabase::exec(const QString& q, QVariantList& data)
{
    QSqlQuery query(QSqlDatabase::database(activeDb));
    query.prepare(q);
    query.exec();

    while (query.next()) {
      QSqlRecord record = query.record();
      int count = record.count();
      QVariantMap map;
      for(int i = 0; i < count; ++i) {
        map[record.field(i).name()] = record.value(i);
      }
      data.push_back(map);
    }
}

 

main.cpp

#include "sqldatabase.h"

int main(int argc, char *argv[])
{
    SQLDatabase database;
    auto path = QString("%1%2").arg(qApp->applicationDirPath()).arg("/phonebook.db");

    QSqlError err = database.addConnection("QSQLITE", path, "phonebook");

    if (err.type() != QSqlError::NoError)
        qDebug() << QString("%1,%2").arg("Unable to open database An error occurred while opening the connection: " + err.text());

    /* create */
    database.exec("create table phonebook (id int primary key, "
                   "name TEXT NOT NULL, number  INT NOT NULL)");

    /* insert */
    database.exec("insert into phonebook values(102, 'makersweb', '1012341234')");


    /* select */
    QString id("102");
    QVariantList data;
    database.exec("select * from phonebook where id = " "'" + id + "'", data);

    for(const auto &item: data){
        auto map = item.toMap();
        qDebug() << map["number"].toInt();
    }
}

 

실제 만들어진 db를 열어보면 아래 그림과 같이 확인할 수 있다.

db.png

TAG •
  • ?
    민토고 2020.05.20 08:55

    한글같은 유니코드 문자를 sql 쿼리의 컬럼 값으로 쓰려면 어떻게 해야 할까요?


  1. No Image notice

    Qt프로그래밍(QtQuick) Beginner를 위한 글 읽는 순서

    Date2019.01.05 CategoryQML and Qt Quick By운영자 Views109984
    read more
  2. 가상키보드(Qt Virtual Keyboard)를 사용하는 방법

    Date2019.05.03 CategoryMobile and Embedded Bymakersweb Views235093
    Read More
  3. Windows에서 Qt D-Bus를 사용하여 프로세스간 통신(IPC)

    Date2019.05.02 CategoryGeneral and Desktop Bymakersweb Views7340
    Read More
  4. No Image

    QML과 QtQuick 모듈 개념과 기본 타입들

    Date2019.04.26 CategoryQML and Qt Quick Bymakersweb Views15503
    Read More
  5. QML 전역 객체 (Global Object)

    Date2019.04.10 CategoryQML and Qt Quick Bymakersweb Views2695
    Read More
  6. tslib의 ts_calibrate를 응용해서 Qt로 터치보정기능 구현

    Date2019.04.06 CategoryQML and Qt Quick Bymakersweb Views3111
    Read More
  7. No Image

    GPU가 없는 장치에서 Qt Quick을 사용

    Date2019.04.02 CategoryQML and Qt Quick Bymakersweb Views4269
    Read More
  8. No Image

    QTextCodec클래스를 사용하여 유니코드와 EUC-KR 변환

    Date2019.03.25 CategoryGeneral and Desktop Bymakersweb Views5951
    Read More
  9. No Image

    qInstallMessageHandler를 이용한 디버그 메세지 출력 제어하기

    Date2019.02.25 CategoryGeneral and Desktop Bymakersweb Views3625
    Read More
  10. Qt5기반 독립 프로세스(out-of-process)로 동작하는 가상키보드(virtual keyboard)

    Date2019.02.24 CategoryMobile and Embedded Bymakersweb Views5114
    Read More
  11. Qml 기본 컴포넌트 강좌 (4) - 모델 리스팅(Listing)

    Date2019.02.23 CategoryQML and Qt Quick By운영자 Views7401
    Read More
  12. Qt Bluetooth를 이용한 시리얼(Serial) 통신

    Date2019.02.17 CategoryMobile and Embedded Bymakersweb Views6298
    Read More
  13. Qml 기본 컴포넌트 강좌 (3) - 배치(positioning) 컴포넌트

    Date2019.02.10 CategoryQML and Qt Quick By운영자 Views7706
    Read More
  14. No Image

    QString 문자열 다루기 예제

    Date2019.01.26 CategoryGeneral and Desktop By운영자 Views47019
    Read More
  15. Qt SQL을 이용한 가벼운 데이터베이스 다루기

    Date2019.01.23 CategoryGeneral and Desktop By운영자 Views9508
    Read More
  16. 구글 클라우드 Speech-To-Text API를 Qt기반(C++, Qml)테스트

    Date2019.01.20 CategoryGeneral and Desktop Bymakersweb Views5145
    Read More
  17. No Image

    QNetworkAccessManager를 통해 HTTP POST 하는 예제

    Date2019.01.17 CategoryGeneral and Desktop Bymakersweb Views7101
    Read More
  18. Qt응용프로그램 실행 시 콘솔창(터미널)같이 띄우기

    Date2019.01.16 CategoryGeneral and Desktop Bymakersweb Views7203
    Read More
  19. 안드로이드 가상장치 사용

    Date2019.01.13 CategoryMobile and Embedded Bymakersweb Views3341
    Read More
  20. No Image

    Qml 기본 컴포넌트 강좌 (2)

    Date2019.01.05 CategoryQML and Qt Quick Bymakersweb Views10938
    Read More
  21. Qml 기본 컴포넌트 강좌 (1)

    Date2019.01.03 CategoryQML and Qt Quick Bymakersweb Views15232
    Read More
Board Pagination Prev 1 5 6 7 8 9 Next
/ 9