Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
IBCPSession2::BCPSetBulkMode proporciona una alternativa a IBCPSession::BCPColFmt (OLE DB) para especificar el formato de columna. A diferencia de IBCPSession::BCPColFmt, que establece atributos de formato de columna individuales, IBCPSession2::BCPSetBulkMode establece todos los atributos.
Sintaxis
HRESULT BCPSetBulkMode (
int property,
void * pField,
int cbField,
void * pRow,
int cbRow
);
Argumentos
propiedad
Constante de tipo BYTE. Consulte la tabla de la sección Comentarios para obtener una lista de las constantes.
pField
Puntero al valor del terminador de campo.
cbField
Longitud en bytes del valor del terminador de campo.
proa
Puntero al valor del terminador de fila.
cbRow
Longitud en bytes del valor del terminador de fila.
Devoluciones
IBCPSession2::BCPSetBulkMode puede devolver una de las siguientes opciones:
S_OK |
El método se ha llevado a cabo de forma correcta. |
E_FAIL |
Se produjo un error específico del proveedor para obtener información detallada sobre el uso de la interfaz ISQLServerErrorInfo. |
E_UNEXPECTED |
No se esperaba la llamada al método. Por ejemplo, no se llamó al IBCPSession2::BCPInit método antes de llamar a IBCPSession2::BCPSetBulkMode. |
E_INVALIDARG |
El argumento no era válido. |
E_OUTOFMEMORY |
Error de memoria insuficiente. |
Observaciones
IBCPSession2::BCPSetBulkMode se puede usar para copiar de forma masiva una consulta o una tabla. Cuando IBCPSession2::BCPSetBulkMode se usa para copiar de forma masiva una instrucción de consulta, se debe llamar antes de llamar IBCPSession::BCPControl(BCP_OPTIONS_HINTS, ...) a para especificar la instrucción de consulta.
Debe evitar combinar la sintaxis de llamada RPC con sintaxis de consulta por lotes ({rpc func};SELECT * from Tblpor ejemplo) en un solo texto de comando. Esto hará que ICommandPrepare::P repare devuelva un error y le impida recuperar metadatos. Use la sintaxis ODBC CALL ({call func}; SELECT * from Tblpor ejemplo) si necesita combinar la ejecución de procedimientos almacenados y la consulta por lotes en un solo texto de comando.
En la tabla siguiente se enumeran las constantes para el parámetro de propiedad .
| Propiedad | Descripción |
|---|---|
| BCP_OUT_CHARACTER_MODE | Especifica el modo de salida de caracteres. Corresponde a la opción -c de BCP.EXE y a IBCPSession::BCPColFmt con la propiedad eUserDataType establecida BCP_TYPE_SQLCHARACTERen . |
| BCP_OUT_WIDE_CHARACTER_MODE | Especifica el modo de salida Unicode. Corresponde a la opción -w de BCP.EXE e IBCPSession::BCPColFmt con la propiedad eUserDataType establecida BCP_TYPE_SQLNCHARen . |
| BCP_OUT_NATIVE_TEXT_MODE | Especifica los tipos nativos para los tipos que no son caracteres y Unicode para los tipos de caracteres. Corresponde a la opción -N de BCP.EXE e IBCPSession::BCPColFmt con la propiedad eUserDataType establecida BCP_TYPE_SQLNCHAR en si el tipo de columna es una cadena o BCP_TYPE_DEFAULT si no es una cadena. |
| BCP_OUT_NATIVE_MODE | Especifica los tipos de base de datos nativos. Corresponde a la opción -n de BCP.EXE e IBCPSession::BCPColFmt con la propiedad eUserDataType establecida BCP_TYPE_DEFAULTen . |
Puede llamar a IBCPSession::BCPControl e IBCPSession2::BCPSetBulkMode para las opciones IBCPSession::BCPControl que no entran en conflicto con IBCPSession2::BCPSetBulkMode. Por ejemplo, puede llamar a IBCPSession::BCPControl con BCP_OPTION_FIRST e IBCPSession2::BCPSetBulkMode.
No se puede llamar a IBCPSession::BCPControl con BCP_OPTION_TEXTFILE e IBCPSession2::BCPSetBulkMode.
Si intenta llamar a IBCPSession2::BCPSetBulkMode con una secuencia de llamadas de función que incluye IBCPSession::BCPColFmt, IBCPSession::BCPControl e IBCPSession::BCPReadFmt, una de las llamadas de función devolverá un error de secuencia. Si decide corregir el error, llame a IBCPSession::BCPInit para restablecer la configuración y empezar de nuevo.
En la tabla siguiente se presentan algunos ejemplos de llamadas de función que producen un error de secuencia de funciones:
Secuencia de llamadas
BCPInit("table", "dataFile", "errorFile", BCP_DIRECTION_IN);
BCPSetBulkMode();
BCPInit("table", "dataFile", "errorFile", BCP_DIRECTION_OUT);
BCPSetBulkMode();
BCPReadFmt();
BCPInit(NULL, "dataFile", "errorFile", BCP_DIRECTION_OUT);
BCPControl(BCP_OPTION_HINTS, "select ...");
BCPSetBulkMode();
BCPInit("table", "dataFile", "errorFile", BCP_DIRECTION_OUT);
BCPSetBulkMode();
BCPColFmt();
BCPInit("table", "dataFile", "errorFile", BCP_DIRECTION_OUT);
BCPControl(BCP_OPTION_DELAYREADFMT, true);
BCPReadFmt();
BCPColFmt();
BCPInit(NULL, "dataFile", "errorFile", BCP_DIRECTION_OUT);
BCPControl(BCP_OPTION_DELAYREADFMT, true);
BCPSetBulkMode();
BCPControl(BCP_OPTION_HINTS, "select ...");
BCPReadFmt();
BCPInit("table", "dataFile", "errorFile", BCP_DIRECTION_OUT);
BCPControl(BCP_OPTION_DELAYREADFMT, true);
BCPColumns();
BCPInit("table", "dataFile", "errorFile", BCP_DIRECTION_OUT);
BCPControl(BCP_OPTION_DELAYREADFMT, true);
BCPSetColFmt();
Ejemplo
En el ejemplo siguiente se crean cuatro archivos con diferentes configuraciones de IBCPSession2::BCPSetBulkMode.
// compile with: sqlncli11.lib oleaut32.lib ole32.lib
#include <stdio.h>
#include "sqlncli.h"
IDBInitialize* g_pIDBInitialize = NULL;
IBCPSession2 * g_pIBcpSession = NULL;
class COLEDBPropSet : public DBPROPSET {
public:
COLEDBPropSet() {
rgProperties = NULL;
cProperties = 0;
};
COLEDBPropSet(const GUID& guid) {
rgProperties = NULL;
cProperties = 0;
guidPropertySet = guid;
};
~COLEDBPropSet() {
for ( ULONG i = 0 ; i < cProperties ; i++ )
VariantClear(&rgProperties[i].vValue);
CoTaskMemFree(rgProperties);
}
void SetGUID(const GUID& guid) {
guidPropertySet = guid;
};
bool AddProperty(DWORD dwPropertyID, bool bValue) {
if (!Add())
return false;
rgProperties[cProperties].dwPropertyID = dwPropertyID;
rgProperties[cProperties].vValue.vt = VT_BOOL;
rgProperties[cProperties].vValue.boolVal = (bValue) ? VARIANT_TRUE : VARIANT_FALSE;
cProperties++;
return true;
};
bool AddProperty(DWORD dwPropertyID, long nValue) {
if (!Add())
return false;
rgProperties[cProperties].dwPropertyID = dwPropertyID;
rgProperties[cProperties].vValue.vt = VT_I4;
rgProperties[cProperties].vValue.lVal = nValue;
cProperties++;
return true;
};
bool AddProperty(DWORD dwPropertyID,LPCWSTR szValue) {
if (!Add())
return false;
rgProperties[cProperties].dwPropertyID = dwPropertyID;
rgProperties[cProperties].vValue.vt = VT_BSTR;
rgProperties[cProperties].vValue.bstrVal = SysAllocString(szValue);
cProperties++;
return true;
};
bool Add() {
DBPROP* p = (DBPROP*)CoTaskMemRealloc(rgProperties, (cProperties + 1) * sizeof(DBPROP));
if (p != NULL) {
rgProperties = p;
rgProperties[cProperties].dwOptions = DBPROPOPTIONS_REQUIRED;
rgProperties[cProperties].colid = DB_NULLID;
rgProperties[cProperties].vValue.vt = VT_EMPTY;
return true;
}
else
return false;
};
};
void OLEDBCleanUp() {
if (g_pIDBInitialize) {
g_pIDBInitialize->Release();
g_pIDBInitialize = NULL;
}
if (g_pIBcpSession) {
g_pIBcpSession->Release();
g_pIBcpSession = NULL;
}
}
BOOL MakeOLEDBConnect(LPWSTR pServer) {
BOOL ret = true;
IDBProperties * pIDBProperties = NULL;
IDBCreateSession * pIDBCreateSession = NULL;
COLEDBPropSet PropSet(DBPROPSET_DBINIT);
COLEDBPropSet BcpProperty(DBPROPSET_SQLSERVERDATASOURCE);
try {
HRESULT hr = CoInitializeEx(NULL,COINIT_MULTITHREADED);
hr = CoCreateInstance(SQLNCLI_CLSID, NULL, CLSCTX_INPROC_SERVER, IID_IDBInitialize, (LPVOID *)&g_pIDBInitialize);
if (FAILED(hr)) {
printf("CoCreateInstance failed\n");
return false;
}
PropSet.AddProperty(DBPROP_INIT_DATASOURCE, (LPWSTR)pServer);
PropSet.AddProperty(DBPROP_AUTH_INTEGRATED, L"SSPI");
hr = g_pIDBInitialize->QueryInterface(IID_IDBProperties, (void**) &pIDBProperties);
if (FAILED(hr)) {
printf("g_pIDBInitialize->->QueryInterface(IID_IDBProperties...) failed\n");
throw false;
}
hr = pIDBProperties->SetProperties(1, &PropSet);
if (FAILED(hr)) {
printf("g_pIDBInitialize->->SetProperties(...) failed\n");
throw false;
}
hr = g_pIDBInitialize->Initialize();
if (FAILED(hr)) {
printf("g_pIDBInitialize->->Initialize() failed\n");
throw false;
}
BcpProperty.AddProperty(SSPROP_ENABLEFASTLOAD, true);
BcpProperty.AddProperty(SSPROP_ENABLEBULKCOPY, true);
hr = pIDBProperties->SetProperties(1, &BcpProperty);
if (FAILED(hr)) {
printf("g_pIDBInitialize->->SetProperties() for bcp failed\n");
throw false;
}
hr = g_pIDBInitialize->QueryInterface(IID_IDBCreateSession, (void**) &pIDBCreateSession);
if (FAILED(hr)) {
printf("g_pIDBInitialize->QueryInterface(IID_IDBCreateSession..) failed\n");
throw false;
}
hr = pIDBCreateSession->CreateSession(NULL, IID_IBCPSession2, (IUnknown**) &g_pIBcpSession);
if (FAILED(hr)) {
printf("g_pIDBCreateSession->CreateSession() failed\n");
throw false;
}
}
catch(...) {
ret = false;
}
if (pIDBProperties)
pIDBProperties->Release();
if (pIDBCreateSession)
pIDBCreateSession->Release();
return ret;
}
BOOL BCPSetBulkMode(LPWSTR pszServer, LPTSTR pszQureryOut, char BCPType, LPWSTR pszDataFile) {
HRESULThr;
if (!MakeOLEDBConnect(pszServer))
return false;
hr = g_pIBcpSession->BCPInit(NULL, pszDataFile, NULL, BCP_DIRECTION_OUT ); // bcp init for queryout
if (FAILED(hr)) {
printf("BCP init failed\n");
OLEDBCleanUp();
return false;
}
// setbulkmode
char ColTerm[] = "\t";
char RowTerm[] = "\r\n";
wchar_t wColTerm[] = L"\t";
wchar_t wRowTerm[] = L"\r\n";
BYTE * pColTerm = NULL;
int cbColTerm = NULL;
BYTE * pRowTerm = 0;
int cbRowTerm = 0;
int bulkmode = -1;
if(BCPType == 'c') { // bcp -c
pColTerm = (BYTE*)ColTerm;
pRowTerm = (BYTE*)RowTerm;
cbColTerm = 1;
cbRowTerm = 2;
bulkmode = BCP_OUT_CHARACTER_MODE;
}
else
if(BCPType == 'w') { // bcp -w
pColTerm = (BYTE*)wColTerm;
pRowTerm = (BYTE*)wRowTerm;
cbColTerm = 2;
cbRowTerm = 4;
bulkmode = BCP_OUT_WIDE_CHARACTER_MODE;
}
else
if (BCPType == 'n') // bcp -n
bulkmode = BCP_OUT_NATIVE_MODE;
else
if (BCPType == 'N') // bcp -n
bulkmode = BCP_OUT_NATIVE_TEXT_MODE;
else {
printf("unknown bcp mode\n");
OLEDBCleanUp();
return false;
}
hr = g_pIBcpSession->BCPSetBulkMode(bulkmode, pColTerm, cbColTerm, pRowTerm, cbRowTerm);
if (FAILED(hr)) {
printf("BCPSetBulkMode failed\n");
OLEDBCleanUp();
return false;
}
// set queryout TSQL statement
hr = g_pIBcpSession->BCPControl(BCP_OPTION_HINTS, pszQureryOut);
if (FAILED(hr)) {
printf("BCPControl failed\n");
OLEDBCleanUp();
return false;
}
// bcp copy
DBROWCOUNT nRowsInserted = 0;
hr = g_pIBcpSession->BCPExec(&nRowsInserted);
if (FAILED(hr)) {
printf("BCPExec failed\n");
OLEDBCleanUp();
return false;
}
printf("bcp done\n");
OLEDBCleanUp();
return true;
}
int main() {
BCPSetBulkMode(L"localhost", TEXT("SELECT 'this is a bcp -c test', 1,2") , 'c', L"bcpc.dat");
BCPSetBulkMode(L"localhost", TEXT("SELECT 'this is a bcp -w test', 1,2") , 'w', L"bcpw.dat");
BCPSetBulkMode(L"localhost", TEXT("SELECT 'this is a bcp -c test', 1,2") , 'n', L"bcpn.dat");
BCPSetBulkMode(L"localhost", TEXT("SELECT 'this is a bcp -w test', 1,2") , 'N', L"bcp_N.dat");
}