VC :数据库

一、ADO

1、导入ADO动态数据库:

#import "c:\program files\common files\system\ado\maado15.dll" no_namespace rename("EOF","adoEOF")

2、初始化COM环境:

::CoInitalize(NULL);

::CoUninitalize();

3、连接数据库:

_ConnectionPtr pconnect(__uuidof(Connection));

 

pconnect->ConnectionString="Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=BUS";

pconnect->Open("","","",NULL);

4、执行SQL语句:

_RecordsetPtr record(__uuidof(Recordset));

_CommandPtr comd(__uuidof(Command));

 

comd->put_ActiveConnection(_variant_t((IDispatch *)pconnect));

 

5、ADO的其他对象:

Parameter对象、Field对象、Error对象。

 

实例:

1、导入ADO动态数据库:

#import "c:\program files\common files\system\ado\maado15.dll" no_namespace rename("EOF","adoEOF")

2、数据库中的数据和编辑框中的数据交互:

void CTestDlg::OnButton1()

{

       // TODO: Add your control notification handler code here

              UpdateData(true);

       CoInitialize(NULL);

       _ConnectionPtr pconnect(__uuidof(Connection));

       _RecordsetPtr record(__uuidof(Recordset));

       _CommandPtr comd(__uuidof(Command));

       pconnect->ConnectionString="Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=student";

       pconnect->Open("","","",NULL);

       comd->put_ActiveConnection(_variant_t((IDispatch *)pconnect));

       //标准SQL语句

       CString cmda="";

       cmda="select * from 学生信息 where 姓名='";

       cmda+=m_na;cmda+="'";

      

       comd->CommandText=_bstr_t(cmda);//得到SQL语句

       record=comd->Execute(NULL,NULL,adCmdText);

       if(!record->end)

       {

              m_name=(char *)(_bstr_t)record->GetCollect("姓名");

              m_sex=(char *)(_bstr_t)record->GetCollect("性别");

              m_age=(char *)(_bstr_t)record->GetCollect("年龄");

              UpdateData(false);

       }

       else

       {     m_name="";

              m_sex="";

              m_age="";

              UpdateData(false);

              AfxMessageBox("查询不到该学生的信息");

       }

       record->Close();

       pconnect->Close();

       comd.Release();

       record.Release();

       pconnect.Release();

       CoUninitialize();

}

void CTestDlg::OnLogin()

{

       // TODO: Add extra validation here

       UpdateData(true);

       CoInitialize(NULL);

       _ConnectionPtr pconnect(__uuidof(Connection));

       _RecordsetPtr record(__uuidof(Recordset));

       _CommandPtr comd(__uuidof(Command));

       pconnect->ConnectionString="Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=Library";

       pconnect->Open("","","",NULL);

       comd->put_ActiveConnection(_variant_t((IDispatch *)pconnect));

       //标准SQL语句

       CString cmd="select * from READER where NAME='";

       cmd+=m_name;

       cmd+="' AND PASSWORD='";

       cmd+=m_password;

       cmd+="'";

       comd->CommandText=_bstr_t(cmd);//得到SQL语句

       record=comd->Execute(NULL,NULL,adCmdText);

       if(!record->end)

       {    

              CDialog::OnOK();

              CTestDlg2 dlg;

              dlg.DoModal();

 

       }

       else

              AfxMessageBox("LogIn ERROR!");

       record->Close();

       pconnect->Close();

       comd.Release();

       record.Release();

       pconnect.Release();

       CoUninitialize();

}

三、连接Access数据源

1、建立基于单文档的应用程序,利用向导在第(2)步骤选择数据源支持;单击Data Source按钮,弹出Database Option对话框:ODBC下选择相应数据源,弹出选择表对话框。。。。

2、添加控件及相应的变量。

3、利用类向导添加一个新类:CRecordsetAdd : public CRecordset.单击OK,弹出DataBase Option对话框。。。

4、在C*View::DoDataExchange()函数添加如下代码:

void CTestView::DoDataExchange(CDataExchange* pDX)

{

       CRecordView::DoDataExchange(pDX);

       //{{AFX_DATA_MAP(CTestView)

       DDX_Text(pDX, IDC_EDIT1,m_pSet->m_column1);

       DDX_Text(pDX, IDC_EDIT2,m_pSet->m_column2);

       DDX_Text(pDX, IDC_EDIT3,m_pSet->m_column3);

       DDX_Text(pDX, IDC_NA, m_na);

       //}}AFX_DATA_MAP

}

5、在C*View类中,添加函数用于向数据库中添加数据:

void CTestView::OnAdd()

{

       CAddNew dlg;

       CString str;

       if(IDOK==dlg.DoModal())

       {

              try{

              CRecordsetAdd m_pdatabase;

              if(m_pdatabase.IsOpen())

                     m_pdatabase.Close();

              m_pdatabase.Open(CRecordset::snapshot,NULL,CRecordset::none);

              m_pdatabase.AddNew();

 

              m_pdatabase.m_column1=dlg.m_name;

              m_pdatabase.m_column2=dlg.m_sex;

              m_pdatabase.m_column3=dlg.m_age;

              if(m_pdatabase.CanUpdate())

                     m_pdatabase.Update();

              m_pSet->Requery();

              m_pdatabase.Close();

              if(!m_pSet->IsEOF())

                     m_pSet->MoveNext();

              }

              catch(CDBException* e)

              {

                     e->ReportError();

                     return;

              }

              str.Format("添加记录[ %s ]成功",dlg.m_name);

              MessageBox(str,NULL,MB_OK|MB_ICONINFORMATION);

       }

}

6、在C*View类中,添加函数用于删除数据库中的数据:

void CTestView::OnDel()

{

       // TODO: Add your control notification handler code here

              try{

              CString str;

              CRecordsetAdd m_pdatabase;

              if(m_pdatabase.IsOpen())

                     m_pdatabase.Close();

              str.Format("%s",m_pSet->m_column1);

              m_pdatabase.m_strFilter.Format("姓名='%s'",str);

              m_pdatabase.Open(CRecordset::snapshot,NULL,CRecordset::none);

              m_pdatabase.Delete();

 

              if(!m_pdatabase.IsEOF())

                     m_pdatabase.MoveLast();

              else

                     m_pdatabase.SetFieldNull(NULL);

              if(m_pdatabase.IsOpen())

                     m_pdatabase.Close();    

              m_pSet->Requery();

 

              str.Format("删除记录 ["+m_pdatabase.m_column1+"] 成功!{}-..-{}");//如果此处还是写m_pSet->m_name则错误,因为已经重新连接

              MessageBox(str,NULL,MB_OK|MB_ICONINFORMATION);

       }

       catch(CDBException* e)

       {

              e->ReportError();

              return;

       }

}

7、在C*View类中,添加函数用于查询数据库中的数据:

void CTestView::OnQu()

{

       UpdateData(TRUE);

       CString col="姓名";

       m_pSet->Close();

       m_pSet->m_strFilter=col+"='"+m_na+"'";//按字段进行查询

       m_pSet->Open();

       UpdateData(FALSE);

}

 四、设置Access数据库ODBC数据源

注意:控制台应用程序默认是单线程的,因此本程序需要设置MFC的支持,从而可以支持多线程。

       进入Project->Settings->C++, 将Category 选为 Code generation,  再将Use run-time library 选为 Debug multitheaded 就行了 。

 

实例:

//strSourceName是要创建的数据源名, strSourceDb是数据库存放路径, strDescription是数据源的描述字符串

#include <afx.h>

#include <atlbase.h>

#include <iostream.h>

BOOL LoadDbSource(CString strSourceName,CString strSourceDb, CString strDescription)

{

       //存放要打开的子键

       CString strSubKey;

       //检测是否安装了 MS Access ODBC driver:odbcjt32.dll

       //获得 Windows系统目录

       char sysDir[MAX_PATH];

       char drvName[]="\\odbcjt32.dll" ;

       ::GetSystemDirectory (sysDir,MAX_PATH);

       strcat(sysDir,drvName);

       CFileFind findFile;

       if(!findFile.FindFile(sysDir))

       {

              cout<<"您的计算机系统中没有安装 MS Access的 ODBC驱动程序 odbcjt32.dll,您将无法加载该类数据源。"<<endl;

              return false;

       }

       strSubKey="SOFTWARE\\ODBC\\ODBC.INI\\"+strSourceName;

       //创建 ODBC数据源在注册表中的子键

       CRegKey reg;

   reg.Create(HKEY_CURRENT_USER,strSubKey);//创建项file1

   reg.SetValue(strSourceDb,"DBQ");

   reg.SetValue(strDescription,"Description");

   reg.SetValue(sysDir,"Driver");

   reg.SetValue(25,"DriverId");

   reg.SetValue("MS Access;","FIL");

   reg.SetValue("","UID");

   DWORD value=0;

   reg.SetValue(value,"SafeTransactions");

   reg.Close();

       //创建 ODBC数据源的 Jet子键

       strSubKey+="\\Engines\\Jet" ;

       reg.Create(HKEY_CURRENT_USER,strSubKey);//创建Jet子键

       reg.SetValue("","ImplicitCommitSync");

       reg.SetValue(2048,"MaxBufferSize");

       reg.SetValue(5,"PageTimeout");

       reg.SetValue(3,"Threads");

       reg.SetValue("Yes","UserCommitSync");

       //设置 ODBC数据库引擎名称

       reg.Open(HKEY_CURRENT_USER,"SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources");

       CString strDbType="Microsoft Access Driver (*.mdb)";

       reg.SetValue(strDbType,strSourceName);

       cout<<"设置数据源完成"<<endl;

       return true;

}

main()

{

       CString strSourceName="student2";

       CString strSourceDb="D:\\student.mdb";

       CString strDescription="学生信息2";

       LoadDbSource(strSourceName,strSourceDb,strDescription);

}

 

你可能感兴趣的:(数据库)