C++에서 MySQL을 연동하는 방법은 크게 두 가지가 있다고 한다.
C API:
C API를 사용할 때는 더 많은 제어권을 가지고 있지만, 코드가 복잡할 수 있습니다.
직접적인 API 호출과 메모리 관리를 해야 하므로 세심한 주의가 필요합니다.
Connector/C++:
C++ 객체 지향 프로그래밍을 지원하며, 더 직관적인 코드 작성을 지원합니다.
객체 지향적인 접근 방식을 사용하여 관리와 유지 보수가 더 쉬울 수 있습니다.
결론:
C++ 객체 지향 프로그래밍을 선호하고, 코드의 가독성과 유지 보수를 중시한다면 MySQL Connector/C++를 사용하는 것이 좋습니다.
저수준 제어가 필요하거나, 라이브러리의 무게를 줄이고 싶다면 MySQL C API를 사용할 수 있습니다.
그리하여 Connector/C++ 라이브러리를 사용하려 한다.
다운로드 & 설치
MySQL은 기본적으로 설치가 되어있어야 한다.
디버그모드는 디버그 zip파일을 받아야한다.
https://dev.mysql.com/downloads/connector/cpp/
MySQL :: Download Connector/C++
Select Operating System: Select Operating System… Microsoft Windows Ubuntu Linux Debian Linux SUSE Linux Enterprise Server Red Hat Enterprise Linux / Oracle Linux Fedora Linux - Generic Oracle Solaris macOS Source Code Select OS Version: All Windows (x86
dev.mysql.com
VS 환경설정
include 설정
lib 설정
링커 종속성 추가
// pch.h
#ifdef _DEBUG
#pragma comment(lib, "MySQL\\Debug\\mysqlcppconn.lib")
#else
#pragma comment(lib, "MySQL\\Release\\mysqlcppconn.lib")
#endif
동적 라이브러리 추가
사용 예제
#include "pch.h"
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/prepared_statement.h>
int main() {
try {
// MySQL 드라이버 인스턴스를 가져옵니다.
sql::Driver* driver = get_driver_instance();
// 데이터베이스에 연결합니다.
const string server = "tcp://127.0.0.1:3306";
const string name = "root";
const string password = "";
std::unique_ptr<sql::Connection> conn(driver->connect(server, name, password));
// 데이터베이스 작업을 수행합니다.
conn->setSchema("testdb");
// 쿼리 실행
std::unique_ptr<sql::Statement> stmt(conn->createStatement());
std::unique_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT * FROM user"));
// 결과 처리
while (res && res->next()) {
std::cout << res->getString(1) << " " << res->getString(2) << std::endl;
}
}
catch (sql::SQLException& e) {
std::cerr << "SQLException: " << e.what() << std::endl;
std::cerr << "Error code: " << e.getErrorCode() << std::endl;
std::cerr << "SQL state: " << e.getSQLState() << std::endl;
}
catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
catch (...) {
std::cerr << "Unknown exception occurred" << std::endl;
}
return 0;
}
'Server > C++' 카테고리의 다른 글
JSON 사용하기 - nlohmann json (1) | 2024.11.20 |
---|---|
Boost 라이브러리 사용하기 (0) | 2024.11.19 |
Google Protobuf - 4) 자동화 - 2 (0) | 2024.08.21 |
Google Protobuf - 3) 자동화 - 1 (0) | 2024.08.21 |
Google Protobuf - 2) 패킷 송수신 (0) | 2024.08.21 |