Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Archives
Today
Total
관리 메뉴

Yejom's Dev Log

[C++] Visual Studio 외부 라이브러리 추가 본문

Smart Factory Bootcamp

[C++] Visual Studio 외부 라이브러리 추가

Yejom 2024. 6. 28. 14:42

[라이브러리]

- 사전적 의미: 자주 사용하는 코드의 집합

 

*C++에서는?

- .lib 파일 또는 .dll 파일 등을 지칭

- 자주 사용하는 함수, 클래스의 코드를 노출시키지 않고 공유 가능

- .lib, .dll 파일과 연결된 .h (헤더) 파일을 통해 함수 또는 클래스 원형(입출력 & 식별자) 확인 가능

 

[API, 라이브러리, Framework]
라이브러리
: 응용 프로그램 개발을 위해 필요한 함수, 클래스 등을 모아놓은


API (Application Programming Interface)
- 이상의 컴포넌트(시스템, 프로세스, 플렛폼, 프로그램 ) 간에 상호작용 위해 정의된 인터페이스
- 라이브러리와 마찬가지로 함수, 클래스 등으로 제공됨


Framework
: 응용 프로그램 개발을 위해 사용되는 전체적인 또는 구조


[ .lib와 .dll ]

lib (library)
- "정적 라이브러리"
- C++ 소스코드를 컴파일하고 나온 obj(오브젝트) 파일을 링킹하여 exe 파일을 생성하는 과정 포함됨


dll (dynamic link library)
- "동적 라이브러리
- 런타임에서 dll 위치를 찾고 링킹

 

*** 차이 ***

lib 파일은 컴파일에 성공하면 .exe 파일에 내장됨

.dll 파일은 컴파일을 해도 .exe내장되지 않기 때문에 프로그램을 완성한 뒤에지정된 위치에 .dll 파일이 존재해야


[MySQL 과 C++ 연결]

https://zany-mail-a17.notion.site/C-MySQL-Window-334f8ee67cf945f6b9203e62bed66695

 

C++ MySQL 연결 (Window) | Notion

교육장에서 제공되는 교육자료는 외부 반출 금지입니다. 타인에게 공유 등의 행위를 하지 말아주세요.

zany-mail-a17.notion.site

 

- DB Version 확인

C:\Users\강예정>mysql -V
mysql  Ver 8.0.37 for Win64 on x86_64 (MySQL Community Server - GPL)

 

Visual Studio

// * DEBUG
// 코드 최적화 없음
//** 속도 차이가 10배 정도 생김
//** 용량 차이는 4배 정도 생김
//** 개발 중에는 Debug, 실제 사용자에게 전달될 때 Release

 

MySQL

-- cpp_db 이름의 데이터베이스 생성
CREATE DATABASE cpp_db CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

-- user 이름의 사용자 생성
CREATE USER 'user'@'localhost' IDENTIFIED BY '1234';

-- user 사용자에게 모든 권한 부여
GRANT ALL PRIVILEGES ON *.* TO 'user'@'localhost' WITH GRANT OPTION;

-- user 목록 확인
SELECT user FROM mysql.USER;

Visual Studio - 테이블 연결, 생성, 읽기, 업데이트, 삭제

#include <stdlib.h>
#include <iostream>

#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/prepared_statement.h>
using namespace std;

// for demonstration only. never save your password in the code!
const string server = "tcp://127.0.0.1:3306"; // 데이터베이스 주소
const string username = "user"; // 데이터베이스 사용자
const string password = "1234"; // 데이터베이스 접속 비밀번호

int main()
{
    // MySQL Connector/C++ 초기화
    sql::Driver* driver; // 추후 해제하지 않아도 Connector/C++가 자동으로 해제해 줌
    sql::Connection* con;
    sql::Statement* stmt;
    sql::PreparedStatement* pstmt;
    sql::ResultSet* result;

    try
    {
        driver = get_driver_instance();
        con = driver->connect(server, username, password);
    }
    catch (sql::SQLException e)
    {
        cout << "Could not connect to server. Error message: " << e.what() << endl;
        system("pause");
        exit(1);
    }

    // please create database "cpp_db" ahead of time
    con->setSchema("cpp_db");


    // connector에서 한글 출력을 위한 셋팅 
    stmt = con->createStatement(); // 추가!!
    stmt->execute("set names euckr"); // 추가!!
    if (stmt) { delete stmt; stmt = nullptr; } // 추가!!

    // 데이터베이스 쿼리 실행
    stmt = con->createStatement();
    stmt->execute("DROP TABLE IF EXISTS inventory");
    cout << "Finished dropping table (if existed)" << endl;
    stmt->execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);");
    cout << "Finished creating table" << endl;
    delete stmt;

    pstmt = con->prepareStatement("INSERT INTO inventory(name, quantity) VALUES(?,?)");
    pstmt->setString(1, "banana");
    pstmt->setInt(2, 150);
    pstmt->execute();
    cout << "One row inserted." << endl;

    pstmt->setString(1, "orange");
    pstmt->setInt(2, 154);
    pstmt->execute();
    cout << "One row inserted." << endl;

    pstmt->setString(1, "apple");
    pstmt->setInt(2, 100);
    pstmt->execute();
    cout << "One row inserted." << endl;

    // Select
    pstmt = con->prepareStatement("SELECT * FROM inventory;");
    result = pstmt->executeQuery();

    while (result->next()) {
        printf("Reading from table=(%d, %s, %d)\n", result->getInt(1), result->getString(2).c_str(), result->getInt(3));
    }

    // Update
    pstmt = con->prepareStatement("UPDATE inventory SET quantity = ? WHERE name = ?");
    pstmt->setInt(1, 200);
    pstmt->setString(2, "banana");
    pstmt->executeQuery();
    printf("Row updated\n");

    // Delete
    pstmt = con->prepareStatement("DELETE FROM inventory WHERE name = ?");
    pstmt->setString(1, "orange");
    result = pstmt->executeQuery();
    printf("Row deleted\n");

    // Select
    pstmt = con->prepareStatement("SELECT * FROM inventory;");
    result = pstmt->executeQuery();

    while (result->next()) {
        printf("Reading from table=(%d, %s, %d)\n", result->getInt(1), result->getString(2).c_str(), result->getInt(3));
    }

    // MySQL Connector/C++ 정리
    delete result;
    delete pstmt;
    delete con;
    system("pause");
    return 0;
}

 

https://learn.microsoft.com/ko-kr/azure/mysql/single-server/connect-cpp#connect-create-table-and-insert-data

 

 

빠른 시작: C++를 사용하여 연결 - Azure Database for MySQL

이 빠른 시작에서는 MySQL용 Azure Database에서 데이터를 연결하고 쿼리하는 데 사용할 수 있는 C++ 코드 샘플을 제공합니다.

learn.microsoft.com

 

'Smart Factory Bootcamp' 카테고리의 다른 글

socket  (0) 2024.06.28
[C++] thread  (0) 2024.06.27
[C++ 입문] 7. structure, class  (0) 2024.05.14
[C++ 입문] 6. file separation, namespace  (0) 2024.05.09
[C++ 입문] 5. list, string  (0) 2024.04.30