ado访问数据库的最简模型

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZHANGKUN35268/article/details/40862847

环境:vc++ 6.0, MFC exe,

开始:

第一步:  在头文件中找到 StdAfx.h,在 #endif  下面  添加

#import "c:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","rsEOF")


 

第二步:在APP类里。***App::InitInstance()函数中。 AfxEnableControlContainer();语句下插入:

 if(!AfxOleInit())//这就是初始化COM库
 {
  AfxMessageBox("OLE初始化出错!");
  return FALSE;
 }



 

第三步:新建类(C++类,不基于其他类)

class Database  
{
public:
	Database();
	virtual ~Database();

	//连接数据库
	BOOL OpenMDB(CString strPath);
	//关闭数据库
	void Close();
	void Execute_sql();      //在数据库内新建表
	void Execute_sql2();      //插入指定字段值
	CString locaTime();	//获得当前 年月日时分秒
	
public:
	_ConnectionPtr m_pConn;
};


 

//全局变量 
CString TableName;
Database::Database()
{

}

Database::~Database()
{

}

BOOL Database::OpenMDB(CString strPath)
{
	//1 创建Connection对象
	HRESULT nRet=
		m_pConn.CreateInstance(__uuidof(Connection));
	if (FAILED(nRet))
	{
		return FALSE;
	}
	//2 连接数据库
	CString strConn;
	strConn.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;",strPath);
//	AfxMessageBox(strConn);			这一句可以弹框,看看连接字符串的内容
	nRet=m_pConn->Open(_bstr_t(strConn),"","",-1);
	if (FAILED(nRet))
	{
		return FALSE;
	}
	return TRUE;
}
void Database::Close()
{
	m_pConn->Close();
}

void Database::Execute_sql()
{
	_variant_t RecordsAffected; 
	//users是表名,这个可以用当前时间代替,表名必须以字母开头。
	//m_pConn->Execute("CREATE TABLE users(ID INTEGER, username TEXT, age INTEGER, birthday DATETIME)", &RecordsAffected, adCmdText);
	CString CreateSql;
	TableName = locaTime();
	CreateSql.Format("CREATE TABLE n%s(ID INTEGER, username TEXT, age INTEGER, birthday DATETIME);", TableName);
	m_pConn->Execute((_bstr_t)CreateSql, &RecordsAffected, adCmdText);
}

void Database::Execute_sql2()
{
	_variant_t RecordsAffected; 
	CString ExecuteSql;
	ExecuteSql.Format("INSERT INTO n%s (age) VALUES (22);", TableName);
	m_pConn->Execute((_bstr_t)ExecuteSql, &RecordsAffected, adCmdText);
	//m_pConn->Execute("INSERT INTO users (age) VALUES (22)", &RecordsAffected, adCmdText);	
	// INSERT INTO users (age) VALUES (22);
}
CString Database::locaTime()
{
	/*得到当前系统时间*/
	CTime ctime=CTime::GetCurrentTime();		
	/* 给AutoNewMDB ()备用*/
	CString nowYear, nowMoon, nowDay, nowhour,nowmin,nowsec;	
	nowYear =ctime.Format("%Y");
	nowMoon =ctime.Format("%m");
	nowDay =ctime.Format("%d");
	nowhour =ctime.Format("%H");
	nowmin =ctime.Format("%M");
	nowsec =ctime.Format("%S");
	return nowYear+nowMoon+nowDay+nowhour+nowmin+nowsec;
}


  

调用部分:

#include "Database.h"		//在CPP中包含这个头文件,是因为只在这里用到数据库。
         Database dbse;
	 CFileDialog dlg(TRUE);
	 if (IDCANCEL==dlg.DoModal())
	 {
		 return;
	 }
	 if (!dbse.OpenMDB(dlg.GetPathName()))
	 {
		 AfxMessageBox("打开数据库失败!");
		 return;
	 }
	 else
	 {
		 AfxMessageBox("打开数据库成功!");
	 }
	 dbse.Execute_sql();
	 dbse.Execute_sql2();
	 AfxMessageBox("执行成功,现在去MDB文件里看看");



 

猜你喜欢

转载自blog.csdn.net/ZHANGKUN35268/article/details/40862847