用c++写一个创建mdb文件的操作
时间: 2023-03-24 20:02:17 浏览: 264
vc++读写mdb 程序
5星 · 资源好评率100%
可以使用以下代码来创建一个mdb文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <conio.h>
#include <ctype.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <io.h>
#include <direct.h>
#include <errno.h>
#include <limits.h>
#include <share.h>
#include <math.h>
#include <float.h>
#include <time.h>
#include <locale.h>
#include <tchar.h>
#include <ole2.h>
#include <msdao.h>
int main()
{
HRESULT hr;
DAO_DBEngine *pDBEngine = NULL;
DAO_Database *pDatabase = NULL;
char *mdbFileName = "test.mdb";
char *tableName = "testTable";
char *fieldName = "testField";
char *fieldType = "Text(255)";
char *indexName = "testIndex";
char *indexField = "testField";
// Initialize COM
hr = CoInitialize(NULL);
if (FAILED(hr))
{
printf("Failed to initialize COM\n");
return 1;
}
// Create DBEngine object
hr = CoCreateInstance(CLSID_DBEngine, NULL, CLSCTX_INPROC_SERVER, IID_IDAO_DBEngine, (void **)&pDBEngine);
if (FAILED(hr))
{
printf("Failed to create DBEngine object\n");
CoUninitialize();
return 1;
}
// Create database
hr = pDBEngine->CreateDatabase(mdbFileName, dbLangGeneral, dbVersion40, &pDatabase);
if (FAILED(hr))
{
printf("Failed to create database\n");
pDBEngine->Release();
CoUninitialize();
return 1;
}
// Create table
hr = pDatabase->CreateTable(tableName, dbLangGeneral, NULL);
if (FAILED(hr))
{
printf("Failed to create table\n");
pDatabase->Close();
pDBEngine->Release();
CoUninitialize();
return 1;
}
// Add field to table
hr = pDatabase->TableDefs->GetItem(tableName)->Fields->Append(fieldName, dbText, 255);
if (FAILED(hr))
{
printf("Failed to add field to table\n");
pDatabase->Close();
pDBEngine->Release();
CoUninitialize();
return 1;
}
// Create index on field
hr = pDatabase->TableDefs->GetItem(tableName)->Indexes->Append(indexName);
if (FAILED(hr))
{
printf("Failed to create index\n");
pDatabase->Close();
pDBEngine->Release();
CoUninitialize();
return 1;
}
hr = pDatabase->TableDefs->GetItem(tableName)->Indexes->GetItem(indexName)->Fields->Append(indexField);
if (FAILED(hr))
{
printf("Failed to add field to index\n");
pDatabase->Close();
pDBEngine->Release();
CoUninitialize();
return 1;
}
// Close database
pDatabase->Close();
pDatabase->Release();
// Release DBEngine object
pDBEngine->Release();
// Uninitialize COM
CoUninitialize();
printf("MDB file created successfully\n");
return ;
}
阅读全文