본문 바로가기
IT/programming

[C/C++] C++ sqlite3 wrapper class

by 어느해겨울 2022. 3. 23.

sqlite3을 활용하는 C++ wrapper class를 남긴다. 매번 sqlite 함수를 사용하여 코드를 짜는건 너무 귀찮기 때문..

 

 

소스코드: class_database.cpp

#include "class_database.h"

// Class: SQLHandler, 데이터베이스 관리
SQLHandler::SQLHandler(string _filename) {
	this->sql_handle = NULL;
	this->open(_filename);

	return ;
}

SQLHandler::~SQLHandler(void) {
	return ;
}

bool SQLHandler::open(string _filename) {
	if( sqlite3_open(_filename.c_str(), &this->sql_handle) == SQLITE_OK ) {
		return true;
	}
		
	return false;   
}

vector<vector<string>> SQLHandler::query(string _query) {
	sqlite3_stmt *statement;
	vector<vector<string>> results;

	if( sqlite3_prepare_v2(this->sql_handle, _query.c_str(), -1, &statement, 0) == SQLITE_OK ) {
		int cols = sqlite3_column_count(statement);
		int result = 0;
		
		while( true ) {
			result = sqlite3_step(statement);
			if( result == SQLITE_ROW ) {
				vector<string> values;
			
				bool is_exist_col = true;
				for( int col = 0 ; col < cols ; col++ ) {
					if( (char *)sqlite3_column_text(statement, col) == NULL ) {
						is_exist_col = false;
						continue;
					}
					values.push_back((char *)sqlite3_column_text(statement, col));
				}

				if( is_exist_col ) {
					results.push_back(values);
				}
			
			} else {
				break;   
			}
		}
	   
		sqlite3_finalize(statement);
	}
	
	string error = sqlite3_errmsg(this->sql_handle);
	if( error != "not an error" ) {
		cout << _query << " " << error << endl;
	}
	
	return results;  
}

void SQLHandler::close(void) {
	sqlite3_close(this->sql_handle);   
	
	return ;
}

 

소스코드: class_database.h

#ifndef __CLASS_DATABASE_H__
#define __CLASS_DATABASE_H__

#include <string>
#include <vector>
#include <iostream>
#include <sqlite3.h>

using namespace std;

class SQLHandler {
	private:
		sqlite3 *sql_handle;

	public:
		SQLHandler(string _filename);
		~SQLHandler(void);
		
		bool open(string _filename);
		vector<vector<string>> query(string _query);
		void close(void);
};

#endif

 

소스코드: main.cpp

#include "class_database.h"

SQLHandler *sql_handler;
sql_handler = new SQLHandler(PATH_DATABASE_FILE);

vector<vector<string>> v_result;
v_result = sql_handler->query("select * from table order by id asc;");
sql_handler->close();

for( int idx = 0 ; idx < (int)v_result.size() ; idx++ ) {
	cout << [idx][0] << "/" << [idx][1] << endl;
}

 

 

출처: https://www.dreamincode.net/forums/topic/122300-sqlite-in-c/

 

SQLite In C++ - C++ Tutorials | Dream.In.Code

 

www.dreamincode.net

 

댓글