1.环境
1.1 下载
1.2 配置
2.cmakelist.txt
cmake_minimum_required(VERSION 3.16)
project(ODBC LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(ODBC main.cpp)
# include_directories可加
# 链接odbc32库
target_link_libraries(ODBC odbc32)
include(GNUInstallDirs)
install(TARGETS ODBC
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
3.测试代码
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <iostream>
int main() {
SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstmt;
SQLRETURN ret;
// 分配环境句柄
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
std::cerr << "SQLAllocHandle (ENV) failed" << std::endl;
return 1;
}
// 设置环境属性
ret = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
std::cerr << "SQLSetEnvAttr failed" << std::endl;
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 1;
}
// 分配连接句柄
ret = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
std::cerr << "SQLAllocHandle (DBC) failed" << std::endl;
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 1;
}
// 连接到数据库
ret = SQLConnect(hdbc, (SQLCHAR*)"test_odbc_mysql", SQL_NTS, (SQLCHAR*)"root", SQL_NTS, (SQLCHAR*)"123456", SQL_NTS);
if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
std::cerr << "SQLConnect failed" << std::endl;
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 1;
}
// 分配语句句柄
ret = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
std::cerr << "SQLAllocHandle (STMT) failed" << std::endl;
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 1;
}
// 执行查询语句
ret = SQLExecDirect(hstmt, (SQLCHAR*)"SELECT * FROM tb_user", SQL_NTS);
if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
std::cerr << "SQLExecDirect failed" << std::endl;
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 1;
}
// 处理结果集(这里简单打印)
SQLSMALLINT numCols;
SQLNumResultCols(hstmt, &numCols);
// 处理结果集--中文打印不了
SQLCHAR buffer[1024];
SQLLEN cbBuffer;
while (SQLFetch(hstmt) == SQL_SUCCESS) {
for (SQLSMALLINT i = 1; i <= numCols; i++) {
SQLGetData(hstmt, i, SQL_C_CHAR, buffer, sizeof(buffer), &cbBuffer);
std::cout << buffer << " ";
}
std::cout << std::endl;
}
// 释放语句句柄
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
// 断开连接
SQLDisconnect(hdbc);
// 释放连接句柄
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
// 释放环境句柄
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 0;
}
4.结果