C++ 创建ACCESS数据库的两种方式

一、 使用msadox.dll创建,不可引用#include

HRESULT hr = S_OK;

	// 创建.MDB文件  命名为test
	//Set ActiveConnection of Catalog to this string
	CString strcnn(_T("Provider=Microsoft.JET.OLEDB.4.0;Data source = C:\\test.mdb"));
	
	try
	{
		ADOX::_CatalogPtr m_pCatalog = NULL;
		hr = m_pCatalog.CreateInstance(__uuidof (ADOX::Catalog));
		
		if(FAILED(hr))
			
		{
			
            _com_issue_error(hr);
			
		}
		
		else
			
			
		{
			m_pCatalog->Create(_bstr_t(strcnn)); //Create MDB
			
		}
	}  
	catch(_com_error &e)
	{
		// Notify the user of errors if any.
		AfxMessageBox(_T("ERR"));
	}
	// 打开数据库链接   创建表格 
		_ConnectionPtr g_pConn;
	try
	{
		g_pConn.CreateInstance(__uuidof(Connection));
		
		g_pConn->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\test.mdb;", 
			"", "", adConnectUnspecified); 
		
		_variant_t   RecordsAffected;
		CString strSql;
		BSTR bstrSQL;
		
		strSql = _T("CREATE TABLE AXISSave(ID INTEGER,X_Axis REAL,Y_Axis REAL,TestResult INTEGER)");
		bstrSQL = strSql.AllocSysString();
		g_pConn->Execute(bstrSQL, &RecordsAffected, adCmdText); 
	}
	catch(_com_error &e)  
	{
		AfxMessageBox(e.ErrorMessage());
		
		g_pConn = NULL;
		g_pConn->Close();
		::CoUninitialize();

	}

二、 使用#ifndef _AFX_NO_DAO_SUPPORT
#include // MFC DAO database classes
#endif // _AFX_NO_DAO_SUPPORT

创建 不可引用msadox.dll

#ifndef _AFX_NO_ADO_SUPPORT
//#import "C:\Workspace\T5\Version1.x\1.0\03.代码工程\00.COMMON\BIN\comm\msadox.dll"


#import "C:\Workspace\T5\Version1.x\1.0\03.代码工程\00.COMMON\BIN\comm\msado15.dll" no_namespace("ADO") rename("EOF","adoEOF")
#endif

CDaoDatabase db;
	CFileFind pFind;
	CString strDBPath = _T("C:\\AAA.MDB");
	CString strTableName = _T("thsoft");

	if (pFind.FindFile(strDBPath)) 
	{
		::DeleteFile(strDBPath);
	}
	db.Create(strDBPath);

	CDaoTableDef table(&db);
	table.Create(strTableName);


	CString str = _T("");
	for(int iFieldNum = 0; iFieldNum < 10; iFieldNum++)
	{
		//DWORD dwFieldID = m_FieldIDs[iFieldNum];
		//VERIFY(GetFieldName(dwFieldID, str));
		
		////
		CDaoFieldInfo pInfo;
		str.Format(_T("%d"), iFieldNum);
		pInfo.m_strName = str ;
		pInfo.m_nType = dbMemo;		//备注
		pInfo.m_lSize = 0;

		pInfo.m_nOrdinalPosition = iFieldNum+1;
		pInfo.m_bAllowZeroLength = true;
		pInfo.m_bRequired = FALSE;
		pInfo.m_lAttributes = dbVariableField | dbUpdatableField;
		pInfo.m_strValidationRule = _T("");
		pInfo.m_strValidationText = _T("");
		pInfo.m_strDefaultValue = _T(""); 
		
		table.CreateField(pInfo);
	}
	
		table.Append();


在析构时要处理dao环境AfxDaoTerm();

你可能感兴趣的:(C/C++,VC,sql)