프로그래밍/SQLite3

SQLite3 MFC 사용법

에어버스 2016. 12. 30. 14:31

 

1. SQLite 공식 홈페이지에서 파일 얻기

1) DLL 파일 얻기

https://sqlite.org/download.html

위 링크에서 Source CodePrecompiled Binaries for Windows (자신의 프로젝트에 따라 x86/x64) 의 zip파일울 다운로드한다.

다운로드한 파일을 압축 풀면 아래와 같이 소스파일과 def, dll 파일이 있다.


 

2) Lib 파일 만들기

VisualStudio 용 개발자 명령 프롬프트 를 실행하여 def 파일로 부터 lib 파일을 만든다.
도스창에서 qlite3.def 파일이 있는 폴더로 이동해서 "lib /def:sqlite3.def /machine:x86" 을 실행하면 sqlite3.lib 파일이 만들어진다.
(만약, 64비트용 바이너리 파일을 다운로드 했다면, "lib /def:sqlite3.def /machine:x64")

MFC에서 아래 3개 파일만 사용한다.    

MFC20161230.zip
다운로드


sqlite3.h 파일은 소스 코드를 다운로드 받은 파일을 압축 풀면 있다.


sqlite3.h    
sqlite3.dll    
sqlite3.lib


2. MFC 프로젝트의 소스가 있는 폴더에 sqlite3.h 와 sqlite3.lib 를 복사하고 sqlite3.dll 은 실행파일이 있는 폴더에 복사한다. (프로젝트 소스와 구분하기 위해 sqlite3 폴더에 복사했다.)

 

MFC해당 소스에 아래 코드를 추가한다.

1
2
3
4
#include "SQLite3\sqlite3.h"
 
#pragma comment("SQLite3\\sqlite3.lib")
 
cs


<DB, 테이블 생성, 데이터 삽입, 데이터 조회하기>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#pragma comment(lib, "SQLite3\\sqlite3.lib"
... 
 
void CSQLiteTestDlg::OnBnClickedButton1()
{
    sqlite3* pDB;
    char* strSQL;
    CString str, strNum, strTrno, strHotime;
    char* pErr, *pDBFile = "Data.db";
    int nResult = sqlite3_open(pDBFile, &pDB);
    if (nResult)
    {
        AfxMessageBox(L"DB 파일을 열지 못했습니다.");
        return;
    }
    str = "DB 생성.\r\n";    
 
    strSQL = "DROP TABLE [tblData]"// 테이블이 있으면 지운다.
    nResult = sqlite3_exec(pDB, strSQL, NULLNULL&pErr); 
 
    strSQL = "CREATE TABLE [tblData] ( \
        [Num] int(11) NOT NULL, \
        [trno] varchar(8) DEFAULT NULL, \
        [hotime] varchar(6) DEFAULT NULL \
        )"// MySQL 자료형으로 지정함, SQLite 자료형 확인하기.    
 
    nResult = sqlite3_exec(pDB, strSQL, NULLNULL&pErr);
    if (nResult)
    {
        AfxMessageBox(L"테이블을 만들기 실패!");
        sqlite3_free(pErr);
        return;
    }
    str += "테이블 생성.\r\n"
 
    strSQL = "INSERT INTO tblData (Num, trno, hotime) VALUES ( 100, 'PHONE', '10:10:10' );";
    nResult = sqlite3_exec(pDB, strSQL, NULLNULL&pErr);
    if (nResult)
    {
        AfxMessageBox(L"데이터 저장 실패!");
        sqlite3_free(pErr);
        return;
    }
    str += "데이터 삽입.\r\n"
 
    strSQL = "SELECT * FROM tblData;";
    char **results = NULL;
    int rows, columns;
    nResult = sqlite3_get_table(pDB, strSQL, &results, &rows, &columns, &pErr);
    // 조회된 데이터의 행과 열의 수를 각각 rows, columns 에 저장한다.
    if (nResult)
    {
        AfxMessageBox(CString(sqlite3_errmsg(pDB)));
        return;
    }
    else
    {
        // Display Table
        for (int rowCtr = 0; rowCtr <= rows; ++rowCtr)
        {
            // 첫번째 행은 테이블의 컬럼 정보를 가져오고 두번째 행부터 데이터가 된다.
            // 데이터만 가져오려면 rowCtr을 1부터 시작한다. 
 
            strNum = (CA2W)results[rowCtr * columns];
            strTrno = (CA2W)results[rowCtr * columns + 1];
            strHotime = (CA2W)results[rowCtr * columns + 2]; 
 
            str += (strNum + L"\t" + strTrno + L"\t" + strHotime + L"\r\n");
            // 아래 /* */ 로 주석처리한걸로 해도 됨. 
 
            /*
            for (int colCtr = 0; colCtr < columns; ++colCtr)
            {
                // Determine Cell Position
                int cellPosition = (rowCtr * columns) + colCtr; 
 
                // Display Cell Value
                //cout.width(12);
                //cout.setf(ios::left);
                //cout << results[cellPosition] << " ";
                str += results[cellPosition];
                //str.AppendChar('\t');
            }
            str += "\r\n";
            // Display Separator For Header
            if (0 == rowCtr)
            {
                for (int colCtr = 0; colCtr < columns; ++colCtr)
                {
                    //cout.width(12);
                    //cout.setf(ios::left);
                    //cout << "~~~~~~~~~~~~ ";
                    str += "~~~~~~~~~~~~ ";
                }
                str += "\r\n";
            }
            */
        }
    }
    AfxMessageBox(str);
    sqlite3_free_table(results); 
 
    // Close Database
    //cout << "Closing MyDb.db ..." << endl;
    sqlite3_close(pDB);
}
cs

<실행결과>

 


3. Tool 설치
1) VisualStudio 아래 그림처럼 도구/확장 및 업데이트 메뉴에서 온라인/VisualStudio 갤러리에서 SQLite/SQL Server Compact Toolbox 추가한다.

 

 

 
VisualStudio를 다시 시작하면 도구메뉴에 Toolbox추가되어 있다.

SQLite/SQL Server Compact Toolbox 실행해서 Data Connections 항목을 마우스 우측버튼 눌러 Add SQLite Connection 선택하고 만들어진 Data.db 파일을 선택한다.

Toolbox에 추가된 DB 가 아래 처럼 나온다.

 

 

 

 - 테이블 데이터를 보려면 아래처럼 뷰어를 설치하라고 뜬다.

https://www.microsoft.com/ko-kr/download/details.aspx?id=6442

에서 다운로드 받아 설치하면 된다. 

ReportViewer.exe
다운로드