在本快速入門中,您將使用 Visual Studio 2022 和更新版本來建置 Windows C++ 主控台應用程式。 該應用程式使用 Microsoft OLE DB Driver 19 for SQL Server 連線至 Azure SQL Database、Microsoft Fabric 中的 SQL 資料庫或 SQL Server。 它會對 AdventureWorksLT 樣本資料執行參數化查詢並驗證結果。
先決條件
- Visual Studio 2022 及以後版本,支援桌面開發與 C++ 工作負載。 此工作負載會安裝本快速入門中使用的 x64 原生工具命令提示字元。 關於開啟它的說明,請參見 使用 64 位元託管開發者命令提示字元捷徑。
- Microsoft OLE DB Driver 19 for SQL Server. 安裝 x64 驅動程式,並同時選擇用戶端元件與軟體開發套件(SDK)。
建立 SQL 資料庫
在以下平台建立或連接 SQL 資料庫:
在此快速入門中,選擇或載入 AdventureWorksLT 樣本資料。
對於 SQL Server 容器,建立容器並用一個指令載入範例資料:
sqlcmd create mssql --accept-eula --using https://aka.ms/AdventureWorksLT.bak
對於現有的 SQL Server 實例,請從 AdventureWorks 範例資料庫還原AdventureWorksLT備份。
此快速入門中的 OLE DB 用戶端應用程式可在 Windows 上運行。 SQL Server 容器可以在其他支援的主機上執行。
確認驅動程式
為你的 Visual Studio 版本開啟 x64 Native Tools 命令提示字元,然後執行以下指令:
Important
這個快速入門中的指令使用命令提示字元語法。 請在 x64 Native Tools 命令提示字元中執行它們,其中提示字元結尾為 >。 不要在 PowerShell 中執行它們,因為那裡的提示字元是以 PS 開頭。
reg query HKCR\MSOLEDBSQL19
此指令會顯示已註冊的 MSOLEDBSQL19 提供者。
設定連線
在 x64 Native Tools 的命令提示字元中設定 OLEDB_CONNECTION_STRING 。 應用程式會從環境中讀取 連接字串,但不會顯示它。
對於 Azure SQL Database 或 Fabric 中的 SQL 資料庫,請使用 Microsoft Entra 互動式認證。 將佔位符替換為 SQL 資源中的伺服器、資料庫及 Microsoft Entra 使用者 ID:
set "OLEDB_CONNECTION_STRING=Provider=MSOLEDBSQL19;Data Source=tcp:<server>,1433;Initial Catalog=<database>;Authentication=ActiveDirectoryInteractive;User ID=<user_id>;Use Encryption for Data=Mandatory;Trust Server Certificate=false;"
在 Fabric 裡的 SQL 資料庫,你的身份需要對資料庫項目有讀取權限。 不支援 SQL 認證。 欲了解更多資訊,請參閱 Microsoft Fabric 中 SQL 資料庫的驗證。
對於已存在且接受 Windows 認證的 SQL Server 實例,請使用 Integrated Security=SSPI:
set "OLEDB_CONNECTION_STRING=Provider=MSOLEDBSQL19;Data Source=tcp:<server>,1433;Initial Catalog=<database>;Integrated Security=SSPI;Use Encryption for Data=Mandatory;Trust Server Certificate=false;"
對於接受 SQL 認證的 SQL Server 實例或容器,請使用 Authentication=SqlPassword:
set "OLEDB_USER_ID=<user_id>"
set "OLEDB_PASSWORD=<password>"
set "OLEDB_CONNECTION_STRING=Provider=MSOLEDBSQL19;Data Source=tcp:<server>,1433;Initial Catalog=<database>;Authentication=SqlPassword;User ID=%OLEDB_USER_ID%;Password=%OLEDB_PASSWORD%;Use Encryption for Data=Mandatory;Trust Server Certificate=false;"
SQL Server 憑證必須與伺服器名稱及鏈條對應 Windows 用戶端所信任的認證機構(CA)。 對於 SQL Server 容器,請在容器中設定傳輸層安全(TLS),並在執行應用程式前,先在 Windows 用戶端註冊發出的 CA。 如需詳細資訊,請參閱 在 Linux 上加密 SQL Server 的連線 和 設定 SQL Server Database Engine 以加密連線。
建立應用程式
建立專案目錄:
mkdir oledb-quickstart cd oledb-quickstart使用下列程式碼建立名為
oledb-quickstart.cpp的檔案:#include <windows.h> #include <oledb.h> #include <msdasc.h> #include <msoledbsql.h> #include <cstddef> #include <iomanip> #include <iostream> #include <string> template <typename T> void Release(T*& pointer) { if (pointer != nullptr) { pointer->Release(); pointer = nullptr; } } struct ParameterData { DBSTATUS status; DBLENGTH length; LONG value; }; constexpr std::size_t productNameCharacters = 51; struct RowData { DBSTATUS productIdStatus; DBLENGTH productIdLength; LONG productId; DBSTATUS nameStatus; DBLENGTH nameLength; wchar_t name[productNameCharacters]; }; std::wstring ReadEnvironmentVariable(const wchar_t* name) { const DWORD length = GetEnvironmentVariableW(name, nullptr, 0); if (length == 0) return {}; std::wstring value(length, L'\0'); const DWORD copied = GetEnvironmentVariableW( name, value.data(), length); if (copied == 0 || copied >= length) return {}; value.resize(copied); return value; } int wmain() { const std::wstring connectionString = ReadEnvironmentVariable(L"OLEDB_CONNECTION_STRING"); if (connectionString.empty()) { std::wcerr << L"Set OLEDB_CONNECTION_STRING before running.\n"; return 1; } HRESULT result = CoInitializeEx(nullptr, COINIT_MULTITHREADED); if (FAILED(result)) { std::wcerr << L"COM initialization failed: 0x" << std::hex << result << L'\n'; return 1; } IDataInitialize* dataInitialize = nullptr; IDBInitialize* dbInitialize = nullptr; IDBCreateSession* createSession = nullptr; IDBCreateCommand* createCommand = nullptr; ICommandText* commandText = nullptr; ICommandWithParameters* commandParameters = nullptr; IAccessor* parameterAccessor = nullptr; IRowset* rowset = nullptr; IAccessor* rowAccessor = nullptr; HACCESSOR parameterHandle = DB_NULL_HACCESSOR; HACCESSOR rowHandle = DB_NULL_HACCESSOR; HROW* rows = nullptr; DBCOUNTITEM rowCount = 0; bool initialized = false; do { result = CoCreateInstance( CLSID_MSDAINITIALIZE, nullptr, CLSCTX_INPROC_SERVER, IID_IDataInitialize, reinterpret_cast<void**>(&dataInitialize)); if (FAILED(result)) break; result = dataInitialize->GetDataSource( nullptr, CLSCTX_INPROC_SERVER, connectionString.c_str(), IID_IDBInitialize, reinterpret_cast<IUnknown**>(&dbInitialize)); if (FAILED(result)) break; result = dbInitialize->Initialize(); if (FAILED(result)) break; initialized = true; result = dbInitialize->QueryInterface( IID_IDBCreateSession, reinterpret_cast<void**>(&createSession)); if (FAILED(result)) break; result = createSession->CreateSession( nullptr, IID_IDBCreateCommand, reinterpret_cast<IUnknown**>(&createCommand)); if (FAILED(result)) break; result = createCommand->CreateCommand( nullptr, IID_ICommandText, reinterpret_cast<IUnknown**>(&commandText)); if (FAILED(result)) break; result = commandText->SetCommandText( DBGUID_DBSQL, const_cast<wchar_t*>( L"SELECT TOP (5) ProductID, Name " L"FROM SalesLT.Product " L"WHERE ProductID > ? " L"ORDER BY ProductID;")); if (FAILED(result)) break; result = commandText->QueryInterface( IID_ICommandWithParameters, reinterpret_cast<void**>(&commandParameters)); if (FAILED(result)) break; DB_UPARAMS parameterOrdinal = 1; wchar_t parameterType[] = L"int"; DBPARAMBINDINFO parameterInfo = {}; parameterInfo.pwszDataSourceType = parameterType; parameterInfo.ulParamSize = sizeof(LONG); parameterInfo.dwFlags = DBPARAMFLAGS_ISINPUT; parameterInfo.bPrecision = 10; result = commandParameters->SetParameterInfo( 1, ¶meterOrdinal, ¶meterInfo); if (FAILED(result)) break; result = commandText->QueryInterface( IID_IAccessor, reinterpret_cast<void**>(¶meterAccessor)); if (FAILED(result)) break; DBBINDING parameterBinding = {}; parameterBinding.iOrdinal = 1; parameterBinding.obStatus = offsetof(ParameterData, status); parameterBinding.obLength = offsetof(ParameterData, length); parameterBinding.obValue = offsetof(ParameterData, value); parameterBinding.dwPart = DBPART_STATUS | DBPART_LENGTH | DBPART_VALUE; parameterBinding.dwMemOwner = DBMEMOWNER_CLIENTOWNED; parameterBinding.eParamIO = DBPARAMIO_INPUT; parameterBinding.cbMaxLen = sizeof(LONG); parameterBinding.wType = DBTYPE_I4; parameterBinding.bPrecision = 10; DBBINDSTATUS parameterBindStatus = DBBINDSTATUS_OK; result = parameterAccessor->CreateAccessor( DBACCESSOR_PARAMETERDATA, 1, ¶meterBinding, sizeof(ParameterData), ¶meterHandle, ¶meterBindStatus); if (FAILED(result) || parameterBindStatus != DBBINDSTATUS_OK) { if (SUCCEEDED(result)) result = E_FAIL; break; } ParameterData parameter = { DBSTATUS_S_OK, sizeof(LONG), 0 }; DBPARAMS parameters = { ¶meter, 1, parameterHandle }; result = commandText->Execute( nullptr, IID_IRowset, ¶meters, nullptr, reinterpret_cast<IUnknown**>(&rowset)); if (FAILED(result)) break; result = rowset->QueryInterface( IID_IAccessor, reinterpret_cast<void**>(&rowAccessor)); if (FAILED(result)) break; DBBINDING rowBindings[2] = {}; rowBindings[0].iOrdinal = 1; rowBindings[0].obStatus = offsetof(RowData, productIdStatus); rowBindings[0].obLength = offsetof(RowData, productIdLength); rowBindings[0].obValue = offsetof(RowData, productId); rowBindings[0].dwPart = DBPART_STATUS | DBPART_LENGTH | DBPART_VALUE; rowBindings[0].dwMemOwner = DBMEMOWNER_CLIENTOWNED; rowBindings[0].eParamIO = DBPARAMIO_NOTPARAM; rowBindings[0].cbMaxLen = sizeof(LONG); rowBindings[0].wType = DBTYPE_I4; rowBindings[0].bPrecision = 10; rowBindings[1].iOrdinal = 2; rowBindings[1].obStatus = offsetof(RowData, nameStatus); rowBindings[1].obLength = offsetof(RowData, nameLength); rowBindings[1].obValue = offsetof(RowData, name); rowBindings[1].dwPart = DBPART_STATUS | DBPART_LENGTH | DBPART_VALUE; rowBindings[1].dwMemOwner = DBMEMOWNER_CLIENTOWNED; rowBindings[1].eParamIO = DBPARAMIO_NOTPARAM; rowBindings[1].cbMaxLen = productNameCharacters * sizeof(wchar_t); rowBindings[1].wType = DBTYPE_WSTR; DBBINDSTATUS rowBindStatus[2] = { DBBINDSTATUS_OK, DBBINDSTATUS_OK }; result = rowAccessor->CreateAccessor( DBACCESSOR_ROWDATA, 2, rowBindings, sizeof(RowData), &rowHandle, rowBindStatus); if (FAILED(result) || rowBindStatus[0] != DBBINDSTATUS_OK || rowBindStatus[1] != DBBINDSTATUS_OK) { if (SUCCEEDED(result)) result = E_FAIL; break; } DBCOUNTITEM productsPrinted = 0; while (true) { result = rowset->GetNextRows( DB_NULL_HCHAPTER, 0, 1, &rowCount, &rows); if (FAILED(result) || rowCount == 0) break; RowData row = {}; result = rowset->GetData(rows[0], rowHandle, &row); if (FAILED(result) || row.productIdStatus != DBSTATUS_S_OK || row.productIdLength != sizeof(LONG) || row.nameStatus != DBSTATUS_S_OK || row.nameLength == 0 || row.nameLength % sizeof(wchar_t) != 0 || row.nameLength >= sizeof(row.name)) { result = E_FAIL; break; } row.name[row.nameLength / sizeof(wchar_t)] = L'\0'; if (productsPrinted == 0) { std::wcout << L"Connected with MSOLEDBSQL19.\n\n"; std::wcout << std::left << std::setw(12) << L"Product ID" << L"Name\n"; std::wcout << std::setw(12) << L"----------" << L"----\n"; } std::wcout << std::left << std::setw(12) << row.productId << row.name << L'\n'; ++productsPrinted; result = rowset->ReleaseRows( rowCount, rows, nullptr, nullptr, nullptr); CoTaskMemFree(rows); rows = nullptr; rowCount = 0; if (FAILED(result)) break; } if (FAILED(result)) break; if (productsPrinted == 0) { result = E_FAIL; break; } } while (false); if (rows != nullptr) { if (rowset != nullptr && rowCount != 0) rowset->ReleaseRows(rowCount, rows, nullptr, nullptr, nullptr); CoTaskMemFree(rows); } if (rowHandle != DB_NULL_HACCESSOR && rowAccessor != nullptr) rowAccessor->ReleaseAccessor(rowHandle, nullptr); if (parameterHandle != DB_NULL_HACCESSOR && parameterAccessor != nullptr) parameterAccessor->ReleaseAccessor(parameterHandle, nullptr); Release(rowAccessor); Release(rowset); Release(parameterAccessor); Release(commandParameters); Release(commandText); Release(createCommand); Release(createSession); if (initialized) dbInitialize->Uninitialize(); Release(dbInitialize); Release(dataInitialize); CoUninitialize(); if (FAILED(result)) { std::wcerr << L"OLE DB operation failed: 0x" << std::hex << result << L'\n'; return 1; } return 0; }
連接字串 會傳遞給 IDataInitialize::GetDataSource。 此 API 使用空格關鍵字名稱 Use Encryption for Data 和 Trust Server Certificate。 連線字串請求加密並要求憑證驗證。
查詢使用問號作為參數標記。 應用程式將最小產品 ID 0 繫結為 SQL Server int 型別,從 SalesLT.Product 讀取最多五筆資料列,並列印產品 ID 與名稱。
建置並執行應用程式
在同一 x64 Native Tools 指令提示字元中,找到已安裝的 OLE DB SDK 標頭,並將其目錄存於
OLEDB_INCLUDE:for /f "delims=" %i in ('where /r "%ProgramFiles%\Microsoft SQL Server\Client SDK\OLEDB" msoledbsql.h') do for %j in ("%~dpi.") do set "OLEDB_INCLUDE=%~fj"顯示所選目錄,並確認其包含標頭:
echo %OLEDB_INCLUDE% dir "%OLEDB_INCLUDE%\msoledbsql.h"編譯應用程式:
cl /std:c++17 /EHsc /W4 /I"%OLEDB_INCLUDE%" oledb-quickstart.cpp /link ole32.lib oleaut32.lib執行應用程式:
oledb-quickstart.exe從目前的命令提示字元中清除連線字串:
set OLEDB_CONNECTION_STRING= set OLEDB_USER_ID= set OLEDB_PASSWORD=
產品列會依 AdventureWorksLT 版本有所不同。 輸出類似下列範例:
Connected with MSOLEDBSQL19.
Product ID Name
---------- ----
680 HL Road Frame - Black, 58
706 HL Road Frame - Red, 58
707 Sport-100 Helmet, Red
708 Sport-100 Helmet, Black
709 Mountain Bike Socks, M