ADO.NET 是適用於數據存取的 .NET Framework API,可提供先前數據存取解決方案所無法比擬的功能和便利性。 本節說明一些涉及 ADO.NET 的問題,這些問題是 Visual C++ 使用者所特有的,例如封送處理原生類型。
ADO.NET 在 Common Language Runtime (CLR) 下執行。 因此,任何與 ADO.NET 互動的應用程式也必須以CLR為目標。 不過,這並不表示原生應用程式無法使用 ADO.NET。 這些範例將示範如何從原生程式碼與 ADO.NET 資料庫互動。
封送處理 ADO.NET 的 ANSI 字串
示範如何將原生字串(char *)新增至資料庫,以及如何將 System.String 從資料庫封送至原生字串。
範例
在此範例中,會建立DatabaseClass類別來與 ADO.NET DataTable 對象互動。 請注意,這個類別是原生C++ class (相較於 ref class 或 value class)。 這是必要的,因為我們想要從原生代碼使用此類別,而且您無法在原生代碼中使用受控類型。 這個類別會被編譯成針對 CLR 作為目標,如類別宣告前面的指示詞 #pragma managed 所指示。 如需此指示詞的詳細資訊,請參閱 Managed、Unmanaged。
請注意DatabaseClass類別的私人成員: gcroot<DataTable ^> table。 由於原生類型不能包含受控類型,因此gcroot 關鍵字是必要的。 如需 的詳細資訊 gcroot,請參閱 如何:在原生類型中宣告句柄。
此範例中的其餘程式碼是原生C++程式碼,如前面的#pragma unmanaged指令所示main。 在此範例中,我們會建立DatabaseClass的新實例,並呼叫其方法來建立數據表,並在數據表中填入一些數據列。 請注意,原生C++字串會當做資料庫數據行 StringCol 的值傳遞。 在 DatabaseClass 內,這些字串會使用System.Runtime.InteropServices 命名空間中找到的封送處理功能封送至受管理的字串。 具體來說,方法 PtrToStringAnsi 用來將 char * 封送至 String,而方法 StringToHGlobalAnsi 則用來將 String 封送至 char *。
注意
必須透過呼叫 FreeHGlobal 或 GlobalFree 來釋放由 StringToHGlobalAnsi 配置的記憶體。
// adonet_marshal_string_native.cpp
// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll
#include <comdef.h>
#include <gcroot.h>
#include <iostream>
using namespace std;
#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Runtime::InteropServices;
#define MAXCOLS 100
#pragma managed
class DatabaseClass
{
public:
DatabaseClass() : table(nullptr) { }
void AddRow(char *stringColValue)
{
// Add a row to the table.
DataRow ^row = table->NewRow();
row["StringCol"] = Marshal::PtrToStringAnsi(
(IntPtr)stringColValue);
table->Rows->Add(row);
}
void CreateAndPopulateTable()
{
// Create a simple DataTable.
table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.
DataColumn ^column1 = gcnew DataColumn("StringCol",
Type::GetType("System.String"));
table->Columns->Add(column1);
}
int GetValuesForColumn(char *dataColumn, char **values,
int valuesLength)
{
// Marshal the name of the column to a managed
// String.
String ^columnStr = Marshal::PtrToStringAnsi(
(IntPtr)dataColumn);
// Get all rows in the table.
array<DataRow ^> ^rows = table->Select();
int len = rows->Length;
len = (len > valuesLength) ? valuesLength : len;
for (int i = 0; i < len; i++)
{
// Marshal each column value from a managed string
// to a char *.
values[i] = (char *)Marshal::StringToHGlobalAnsi(
(String ^)rows[i][columnStr]).ToPointer();
}
return len;
}
private:
// Using gcroot, you can use a managed type in
// a native class.
gcroot<DataTable ^> table;
};
#pragma unmanaged
int main()
{
// Create a table and add a few rows to it.
DatabaseClass *db = new DatabaseClass();
db->CreateAndPopulateTable();
db->AddRow("This is string 1.");
db->AddRow("This is string 2.");
// Now retrieve the rows and display their contents.
char *values[MAXCOLS];
int len = db->GetValuesForColumn(
"StringCol", values, MAXCOLS);
for (int i = 0; i < len; i++)
{
cout << "StringCol: " << values[i] << endl;
// Deallocate the memory allocated using
// Marshal::StringToHGlobalAnsi.
GlobalFree(values[i]);
}
delete db;
return 0;
}
StringCol: This is string 1.
StringCol: This is string 2.
編譯程式碼
若要從命令行編譯程式代碼,請將程式代碼範例儲存在名為 adonet_marshal_string_native.cpp 的檔案中,然後輸入下列語句:
cl /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll adonet_marshal_string_native.cpp
封送處理 ADO.NET 的 BSTR 字串
示範如何將 COM 字串(BSTR)新增至資料庫,以及如何將 System.String 從資料庫封送至 BSTR。
範例
在此範例中,會建立DatabaseClass類別來與 ADO.NET DataTable 對象互動。 請注意,這個類別是原生C++ class (相較於 ref class 或 value class)。 這是必要的,因為我們想要從原生碼使用此類別,而且您無法在原生碼中使用 managed 類型。 這個類別會被編譯成以CLR為目標,如類別宣告前面的指示詞 #pragma managed 所指示。 如需此指示詞的詳細資訊,請參閱 Managed、Unmanaged。
請注意DatabaseClass類別的私人成員: gcroot<DataTable ^> table。 因為原生類型不能包含受管理型別,所以需要使用 gcroot 關鍵詞。 如需有關 gcroot 的詳細資訊,請參閱 如何在原生類型中宣告句柄。
此範例中的其餘代碼是原生 C++ 代碼,如 #pragma unmanaged 指令前的標示 main。 在此範例中,我們會建立DatabaseClass的新實例,並呼叫其方法來建立數據表,並在數據表中填入一些數據列。 請注意,COM 字串會當做資料庫數據行 StringCol 的值傳遞。 在 DatabaseClass 內,這些字串會使用在 System.Runtime.InteropServices 命名空間中找到的封送處理功能,封送到 managed 字串。 具體來說,方法 PtrToStringBSTR 用來將 BSTR 封送到 String,方法 StringToBSTR 用來將 String 封送到 BSTR。
注意
由 StringToBSTR 配置的記憶體必須藉由呼叫 FreeBSTR 或 SysFreeString 來釋放。
// adonet_marshal_string_bstr.cpp
// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll
#include <comdef.h>
#include <gcroot.h>
#include <iostream>
using namespace std;
#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Runtime::InteropServices;
#define MAXCOLS 100
#pragma managed
class DatabaseClass
{
public:
DatabaseClass() : table(nullptr) { }
void AddRow(BSTR stringColValue)
{
// Add a row to the table.
DataRow ^row = table->NewRow();
row["StringCol"] = Marshal::PtrToStringBSTR(
(IntPtr)stringColValue);
table->Rows->Add(row);
}
void CreateAndPopulateTable()
{
// Create a simple DataTable.
table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.
DataColumn ^column1 = gcnew DataColumn("StringCol",
Type::GetType("System.String"));
table->Columns->Add(column1);
}
int GetValuesForColumn(BSTR dataColumn, BSTR *values,
int valuesLength)
{
// Marshal the name of the column to a managed
// String.
String ^columnStr = Marshal::PtrToStringBSTR(
(IntPtr)dataColumn);
// Get all rows in the table.
array<DataRow ^> ^rows = table->Select();
int len = rows->Length;
len = (len > valuesLength) ? valuesLength : len;
for (int i = 0; i < len; i++)
{
// Marshal each column value from a managed string
// to a BSTR.
values[i] = (BSTR)Marshal::StringToBSTR(
(String ^)rows[i][columnStr]).ToPointer();
}
return len;
}
private:
// Using gcroot, you can use a managed type in
// a native class.
gcroot<DataTable ^> table;
};
#pragma unmanaged
int main()
{
// Create a table and add a few rows to it.
DatabaseClass *db = new DatabaseClass();
db->CreateAndPopulateTable();
BSTR str1 = SysAllocString(L"This is string 1.");
db->AddRow(str1);
BSTR str2 = SysAllocString(L"This is string 2.");
db->AddRow(str2);
// Now retrieve the rows and display their contents.
BSTR values[MAXCOLS];
BSTR str3 = SysAllocString(L"StringCol");
int len = db->GetValuesForColumn(
str3, values, MAXCOLS);
for (int i = 0; i < len; i++)
{
wcout << "StringCol: " << values[i] << endl;
// Deallocate the memory allocated using
// Marshal::StringToBSTR.
SysFreeString(values[i]);
}
SysFreeString(str1);
SysFreeString(str2);
SysFreeString(str3);
delete db;
return 0;
}
StringCol: This is string 1.
StringCol: This is string 2.
編譯程式碼
若要從命令行編譯程式代碼,請將程式代碼範例儲存在名為 adonet_marshal_string_native.cpp 的檔案中,然後輸入下列語句:
cl /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll adonet_marshal_string_native.cpp
封送 ADO.NET 的 Unicode 字串
示範如何將一個原生的 Unicode 字串(wchar_t *)新增至資料庫,以及如何將資料庫中的 System.String 封送處理為一個原生的 Unicode 字串。
範例
在此範例中,會建立DatabaseClass類別來與 ADO.NET DataTable 對象互動。 請注意,這個類別是原生C++ class (相較於 ref class 或 value class)。 這是必要的,因為我們想要從原生碼使用此類別,而且您無法在原生碼中使用 managed 類型。 這個類別會被編譯成以CLR為目標,如類別宣告前面的指示詞 #pragma managed 所指示。 如需此指示詞的詳細資訊,請參閱 Managed、Unmanaged。
請注意DatabaseClass類別的私人成員: gcroot<DataTable ^> table。 因為原生類型不能包含受管理型別,所以需要使用 gcroot 關鍵詞。 如需有關 gcroot 的詳細資訊,請參閱 如何在原生類型中宣告句柄。
此範例中的其餘代碼是原生 C++ 代碼,如 #pragma unmanaged 指令前的標示 main。 在此範例中,我們會建立DatabaseClass的新實例,並呼叫其方法來建立數據表,並在數據表中填入一些數據列。 請注意,Unicode C++字串會當做資料庫數據行 StringCol 的值傳遞。 在 DatabaseClass 內,這些字串會使用在 System.Runtime.InteropServices 命名空間中找到的封送處理功能,封送到 managed 字串。 具體來說,方法 PtrToStringUni 用來將 wchar_t * 封送到 String,方法 StringToHGlobalUni 用來將 String 封送到 wchar_t *。
注意
由 StringToHGlobalUni 配置的記憶體必須藉由呼叫 FreeHGlobal 或 GlobalFree 來釋放。
// adonet_marshal_string_wide.cpp
// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll
#include <comdef.h>
#include <gcroot.h>
#include <iostream>
using namespace std;
#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Runtime::InteropServices;
#define MAXCOLS 100
#pragma managed
class DatabaseClass
{
public:
DatabaseClass() : table(nullptr) { }
void AddRow(wchar_t *stringColValue)
{
// Add a row to the table.
DataRow ^row = table->NewRow();
row["StringCol"] = Marshal::PtrToStringUni(
(IntPtr)stringColValue);
table->Rows->Add(row);
}
void CreateAndPopulateTable()
{
// Create a simple DataTable.
table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.
DataColumn ^column1 = gcnew DataColumn("StringCol",
Type::GetType("System.String"));
table->Columns->Add(column1);
}
int GetValuesForColumn(wchar_t *dataColumn, wchar_t **values,
int valuesLength)
{
// Marshal the name of the column to a managed
// String.
String ^columnStr = Marshal::PtrToStringUni(
(IntPtr)dataColumn);
// Get all rows in the table.
array<DataRow ^> ^rows = table->Select();
int len = rows->Length;
len = (len > valuesLength) ? valuesLength : len;
for (int i = 0; i < len; i++)
{
// Marshal each column value from a managed string
// to a wchar_t *.
values[i] = (wchar_t *)Marshal::StringToHGlobalUni(
(String ^)rows[i][columnStr]).ToPointer();
}
return len;
}
private:
// Using gcroot, you can use a managed type in
// a native class.
gcroot<DataTable ^> table;
};
#pragma unmanaged
int main()
{
// Create a table and add a few rows to it.
DatabaseClass *db = new DatabaseClass();
db->CreateAndPopulateTable();
db->AddRow(L"This is string 1.");
db->AddRow(L"This is string 2.");
// Now retrieve the rows and display their contents.
wchar_t *values[MAXCOLS];
int len = db->GetValuesForColumn(
L"StringCol", values, MAXCOLS);
for (int i = 0; i < len; i++)
{
wcout << "StringCol: " << values[i] << endl;
// Deallocate the memory allocated using
// Marshal::StringToHGlobalUni.
GlobalFree(values[i]);
}
delete db;
return 0;
}
StringCol: This is string 1.
StringCol: This is string 2.
編譯程式碼
若要從命令行編譯程式代碼,請將程式代碼範例儲存在名為 adonet_marshal_string_wide.cpp 的檔案中,然後輸入下列語句:
cl /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll adonet_marshal_string_wide.cpp
處理 ADO.NET 的 VARIANT 轉換
示範如何將原生 VARIANT 新增至資料庫,以及如何將 System.Object 從資料庫封送處理至原生 VARIANT。
範例
在此範例中,會建立DatabaseClass類別來與 ADO.NET DataTable 對象互動。 請注意,這個類別是原生C++ class (相較於 ref class 或 value class)。 這是必要的,因為我們想要從原生碼使用此類別,而且您無法在原生碼中使用 managed 類型。 這個類別會被編譯成以CLR為目標,如類別宣告前面的指示詞 #pragma managed 所指示。 如需此指示詞的詳細資訊,請參閱 Managed、Unmanaged。
請注意DatabaseClass類別的私人成員: gcroot<DataTable ^> table。 因為原生類型不能包含受管理型別,所以需要使用 gcroot 關鍵詞。 如需有關 gcroot 的詳細資訊,請參閱 如何在原生類型中宣告句柄。
此範例中的其餘代碼是原生 C++ 代碼,如 #pragma unmanaged 指令前的標示 main。 在此範例中,我們會建立DatabaseClass的新實例,並呼叫其方法來建立數據表,並在數據表中填入一些數據列。 請注意,原生 VARIANT 類型會當做資料庫數據行 ObjectCol 的值傳遞。 在 DatabaseClass 內,這些 VARIANT 類型會使用在 System.Runtime.InteropServices 命名空間中找到的封送功能,封送到管理物件。 具體來說,方法 GetObjectForNativeVariant 用來封送 VARIANT 至 Object,而方法 GetNativeVariantForObject 則用來封送 Object 至 VARIANT。
// adonet_marshal_variant.cpp
// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll
#include <comdef.h>
#include <gcroot.h>
#include <iostream>
using namespace std;
#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Runtime::InteropServices;
#define MAXCOLS 100
#pragma managed
class DatabaseClass
{
public:
DatabaseClass() : table(nullptr) { }
void AddRow(VARIANT *objectColValue)
{
// Add a row to the table.
DataRow ^row = table->NewRow();
row["ObjectCol"] = Marshal::GetObjectForNativeVariant(
IntPtr(objectColValue));
table->Rows->Add(row);
}
void CreateAndPopulateTable()
{
// Create a simple DataTable.
table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.
DataColumn ^column1 = gcnew DataColumn("ObjectCol",
Type::GetType("System.Object"));
table->Columns->Add(column1);
}
int GetValuesForColumn(wchar_t *dataColumn, VARIANT *values,
int valuesLength)
{
// Marshal the name of the column to a managed
// String.
String ^columnStr = Marshal::PtrToStringUni(
(IntPtr)dataColumn);
// Get all rows in the table.
array<DataRow ^> ^rows = table->Select();
int len = rows->Length;
len = (len > valuesLength) ? valuesLength : len;
for (int i = 0; i < len; i++)
{
// Marshal each column value from a managed object
// to a VARIANT.
Marshal::GetNativeVariantForObject(
rows[i][columnStr], IntPtr(&values[i]));
}
return len;
}
private:
// Using gcroot, you can use a managed type in
// a native class.
gcroot<DataTable ^> table;
};
#pragma unmanaged
int main()
{
// Create a table and add a few rows to it.
DatabaseClass *db = new DatabaseClass();
db->CreateAndPopulateTable();
BSTR bstr1 = SysAllocString(L"This is a BSTR in a VARIANT.");
VARIANT v1;
v1.vt = VT_BSTR;
v1.bstrVal = bstr1;
db->AddRow(&v1);
int i = 42;
VARIANT v2;
v2.vt = VT_I4;
v2.lVal = i;
db->AddRow(&v2);
// Now retrieve the rows and display their contents.
VARIANT values[MAXCOLS];
int len = db->GetValuesForColumn(
L"ObjectCol", values, MAXCOLS);
for (int i = 0; i < len; i++)
{
switch (values[i].vt)
{
case VT_BSTR:
wcout << L"ObjectCol: " << values[i].bstrVal << endl;
break;
case VT_I4:
cout << "ObjectCol: " << values[i].lVal << endl;
break;
default:
break;
}
}
SysFreeString(bstr1);
delete db;
return 0;
}
ObjectCol: This is a BSTR in a VARIANT.
ObjectCol: 42
編譯程式碼
若要從命令行編譯程式代碼,請將程式代碼範例儲存在名為 adonet_marshal_variant.cpp 的檔案中,然後輸入下列語句:
cl /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll adonet_marshal_variant.cpp
處理 ADO.NET 的 SAFEARRAY 進行封送
示範如何將原生 SAFEARRAY 新增至資料庫,以及如何將受控陣列從資料庫封送至原生 SAFEARRAY。
範例
在此範例中,會建立DatabaseClass類別來與 ADO.NET DataTable 對象互動。 請注意,這個類別是原生C++ class (相較於 ref class 或 value class)。 這是必要的,因為我們想要從原生碼使用此類別,而且您無法在原生碼中使用 managed 類型。 這個類別會被編譯成以CLR為目標,如類別宣告前面的指示詞 #pragma managed 所指示。 如需此指示詞的詳細資訊,請參閱 Managed、Unmanaged。
請注意DatabaseClass類別的私人成員: gcroot<DataTable ^> table。 因為原生類型不能包含受管理型別,所以需要使用 gcroot 關鍵詞。 如需有關 gcroot 的詳細資訊,請參閱 如何在原生類型中宣告句柄。
此範例中的其餘代碼是原生 C++ 代碼,如 #pragma unmanaged 指令前的標示 main。 在此範例中,我們會建立DatabaseClass的新實例,並呼叫其方法來建立數據表,並在數據表中填入一些數據列。 請注意,原生 SAFEARRAY 類型會當做資料庫數據行ArrayIntsCol的值傳遞。 在 DatabaseClass 內,這些 SAFEARRAY 類型會使用在 System.Runtime.InteropServices 命名空間中找到的封送功能,封送到管理物件。 具體而言,方法Copy用來封送SAFEARRAY到受控整數陣列,並且方法Copy用來封送受控整數陣列到SAFEARRAY。
// adonet_marshal_safearray.cpp
// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll
#include <comdef.h>
#include <gcroot.h>
#include <iostream>
using namespace std;
#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Runtime::InteropServices;
#define MAXCOLS 100
#pragma managed
class DatabaseClass
{
public:
DatabaseClass() : table(nullptr) { }
void AddRow(SAFEARRAY *arrayIntsColValue)
{
// Add a row to the table.
DataRow ^row = table->NewRow();
int len = arrayIntsColValue->rgsabound[0].cElements;
array<int> ^arr = gcnew array<int>(len);
int *pData;
SafeArrayAccessData(arrayIntsColValue, (void **)&pData);
Marshal::Copy(IntPtr(pData), arr, 0, len);
SafeArrayUnaccessData(arrayIntsColValue);
row["ArrayIntsCol"] = arr;
table->Rows->Add(row);
}
void CreateAndPopulateTable()
{
// Create a simple DataTable.
table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.
DataColumn ^column1 = gcnew DataColumn("ArrayIntsCol",
Type::GetType("System.Int32[]"));
table->Columns->Add(column1);
}
int GetValuesForColumn(wchar_t *dataColumn, SAFEARRAY **values,
int valuesLength)
{
// Marshal the name of the column to a managed
// String.
String ^columnStr = Marshal::PtrToStringUni(
(IntPtr)dataColumn);
// Get all rows in the table.
array<DataRow ^> ^rows = table->Select();
int len = rows->Length;
len = (len > valuesLength) ? valuesLength : len;
for (int i = 0; i < len; i++)
{
// Marshal each column value from a managed array
// of Int32s to a SAFEARRAY of type VT_I4.
values[i] = SafeArrayCreateVector(VT_I4, 0, 10);
int *pData;
SafeArrayAccessData(values[i], (void **)&pData);
Marshal::Copy((array<int> ^)rows[i][columnStr], 0,
IntPtr(pData), 10);
SafeArrayUnaccessData(values[i]);
}
return len;
}
private:
// Using gcroot, you can use a managed type in
// a native class.
gcroot<DataTable ^> table;
};
#pragma unmanaged
int main()
{
// Create a table and add a few rows to it.
DatabaseClass *db = new DatabaseClass();
db->CreateAndPopulateTable();
// Create a standard array.
int originalArray[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Create a SAFEARRAY.
SAFEARRAY *psa;
psa = SafeArrayCreateVector(VT_I4, 0, 10);
// Copy the data from the original array to the SAFEARRAY.
int *pData;
HRESULT hr = SafeArrayAccessData(psa, (void **)&pData);
memcpy(pData, &originalArray, 40);
SafeArrayUnaccessData(psa);
db->AddRow(psa);
// Now retrieve the rows and display their contents.
SAFEARRAY *values[MAXCOLS];
int len = db->GetValuesForColumn(
L"ArrayIntsCol", values, MAXCOLS);
for (int i = 0; i < len; i++)
{
int *pData;
SafeArrayAccessData(values[i], (void **)&pData);
for (int j = 0; j < 10; j++)
{
cout << pData[j] << " ";
}
cout << endl;
SafeArrayUnaccessData(values[i]);
// Deallocate the memory allocated using
// SafeArrayCreateVector.
SafeArrayDestroy(values[i]);
}
SafeArrayDestroy(psa);
delete db;
return 0;
}
0 1 2 3 4 5 6 7 8 9
編譯程式碼
若要從命令行編譯程式代碼,請將程式代碼範例儲存在名為 adonet_marshal_safearray.cpp 的檔案中,然後輸入下列語句:
cl /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll adonet_marshal_safearray.cpp
.NET Framework 安全性
如需 ADO.NET 安全性問題的相關信息,請參閱 保護 ADO.NET 應用程式。
相關章節
| 區段 | 描述 |
|---|---|
| ADO.NET | 提供 ADO.NET 的概觀,這是一組類別,會將數據存取服務公開給 .NET 程式設計人員。 |
另請參閱
以 C++/CLI 進行 .NET 程式設計 (Visual C++)