MFC中使用ADO读取Access的步骤

1 打开连接:pConnection->Open((_bstr_t)strConnStr, "", "", adModeUnknown);


2 取得所打开文件中所有的表名:

pTableNameRecordset = pConnection->OpenSchema(adSchemaTables);


while(!pTableNameRecordset->adoEOF)
{
_bstr_t table_name = pTableNameRecordset->Fields->GetItem("TABLE_NAME")->Value;   //Get table name inside access file


_bstr_t table_type = pTableNameRecordset->Fields->GetItem("TABLE_TYPE")->Value;  //Get table type of corresponding table 


//if ((LPCTSTR)table_type == L"TABLE")
if(strcmp(table_type, "TABLE") == 0)    //judge the type of table
{
//MessageBox(table_name);
strTableNameList.AddTail(table_name);
}


pTableNameRecordset->MoveNext();
}


3 打开其中某个表:

strSql = L"select * from " + strTableName;


pRecordset->Open((_bstr_t)strSql,   //query all field in table
pConnection.GetInterfacePtr(),  //get the database's IDispatch pointer
adOpenDynamic,
adLockOptimistic,
adCmdText);


4. 取得表中各个字段名的值(即每一列的名字)

for(long j =0;j<pRecordset->Fields->Count;j++)
{
//MessageBox(pRecordset->Fields->Item[j]->GetName());
strColumnNameList.AddTail(pRecordset->Fields->Item[j]->GetName());
}


5. 根据字段名取得字段下每一行的值

while(!pRecordset->adoEOF)
{

rPos = strColumnNameList.GetHeadPosition();
iColumn = 0;
//get item value of every row
while(rPos != NULL)
{
var = pRecordset->GetCollect((_variant_t)(strColumnNameList.GetNext(rPos)));


if ( (iRow) < PREVIEW_ROW && (iColumn) < PREVIEW_COLUMN ) 
{
strSrcDataArray[iRow][iColumn] = var;
}
iColumn++;
//MessageBox((LPCTSTR)_bstr_t(var));
}


iRow++;
pRecordset->MoveNext();
//MessageBox(L"Next");
}

你可能感兴趣的:(File,table,null,database,mfc,Access)