通过 OLE DB 访问受密码保护的数据库

Microsoft SQL Server Compact 4.0 支持的文件级访问控制机制要求在访问受密码保护的 SQL Server Compact 4.0 数据库时必须提供密码。在每次打开数据库时都需要提供此密码。

访问受保护的数据库

使用 DBPROPSET_SSCE_DBINIT 提供程序特定属性集中的 DBPROP_SSCE_DBPASSWORD 属性可指定此属性。在创建数据库时,可以使用此属性为数据库指定数据库密码。加密数据库始终受密码保护。

在压缩数据库时,可以使用该属性将数据库密码更改为新值。

下面的代码示例显示如何打开受密码保护的 SQL Server Compact 4.0 数据库。系统会向用户显示对话框以请求提供密码,此示例没有包含用来显示对话框的代码。

示例

// Object declarations
HRESULT          hr              = NOERROR; 
DBPROPSET        dbpropset[2]; 
DBPROP           dbprop[1]; 
DBPROP           sscedbprop[1]; 
BSTR             pwdPassword; // user input password

// Declare the provider interfaces.
IDBInitialize *  pIDBInitialize  = NULL;
IDBProperties *  pIDBProperties  = NULL;

// Initialize the data source.
CoInitialize(NULL);
hr = CoCreateInstance(CLSID_SQLSERVERCE, 0, CLSCTX_INPROC_SERVER,
    IID_IDBInitialize, (void**) &pIDBInitialize);
if (FAILED(hr))
{
    // Send an error-specific message and do error handling.
    goto Exit;
}

// Initialize property structures.
VariantInit(&dbprop[0].vValue);
VariantInit(&sscedbprop[0].vValue);

// Initialize Property with name of database.
dbprop[0].dwPropertyID = DBPROP_INIT_DATASOURCE;
dbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
dbprop[0].vValue.vt = VT_BSTR;
dbprop[0].vValue.bstrVal = SysAllocString(L"ProtectedData.sdf");
if(NULL == dbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Second property set has one property containing the 
// provider-specific database password in the pwdPassword variable 
// that was obtained from a dialog box (not shown).
sscedbprop[0].dwPropertyID = DBPROP_SSCE_DBPASSWORD;
sscedbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
sscedbprop[0].vValue.vt = VT_BSTR;
sscedbprop[0].vValue.bstrVal = SysAllocString(<pwdPassword>);
if(NULL == sscedbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Initialize property set.
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties = dbprop;
dbpropset[0].cProperties = sizeof(dbprop)/sizeof(dbprop[0]);

// Initialize the provider-specific property set.
dbpropset[1].guidPropertySet = DBPROPSET_SSCE_DBINIT;
dbpropset[1].rgProperties = sscedbprop;
dbpropset[1].cProperties = sizeof(sscedbprop)/sizeof(sscedbprop[0]);

// Set the properties into the provider's data source object.
pIDBInitialize->QueryInterface(IID_IDBProperties,(void**)&pIDBProperties);

hr = pIDBProperties->SetProperties(sizeof(dbpropset)/sizeof(dbpropset[0]), 
    dbpropset);
if(FAILED(hr))
{
    goto Exit;
}

// Initialize the data source.
hr = pIDBInitialize->Initialize();
if(FAILED(hr))
{
   goto Exit;
}

Exit:
// Clean up resources here.

return;