[VC] accessing local database applications using ADO

Source: Internet
Author: User
1. initialize if (! AfxOleInit () {AfxMessageBox (_ T (COM library initialization failed !)); ReturnFALSE;} Initialization Method 2: CoInitialize () CoUninitialize () 2. Import msado15.dll (I put it in stdafx. h) # importmsado15.dllno _ namespacerename (EOF, ADOEOF), rename (BOF, ADOBOF) 3

1. initialize if (! AfxOleInit () {AfxMessageBox (_ T (COM library initialization failed !)); Return FALSE;} method 2 of initialization: CoInitialize () CoUninitialize () 2. Import msado15.dll (I put it in stdafx. h) # import msado15.dllno _ namespace rename (EOF, ADOEOF), rename (BOF, ADOBOF) 3

1. Initialization

If (! AfxOleInit () {AfxMessageBox (_ T ("COM library initialization failed! "); Return FALSE ;}

Method 2:

CoInitialize ()
CoUninitialize ()

2. Import msado15.dll (I put it under stdafx. h)

#import "msado15.dll"no_namespace rename("EOF","ADOEOF"),rename("BOF","ADOBOF")


3. Variable Declaration

_ ConnectionPtr m_pConnection; // _ RecordsetPtr m_pRecordset; CString m_strMdbName; // database name CString m_strMdbPath; // database path CString m_strSQL; // SQL statement CXmlDialog m_xmlDlg; // Save the record set when executing the select statement

4. Connect to the database

Void CMyAdoDlg: OnBnClickedLink () {// TODO: add the control notification handler code here if (m_strMdbName.IsEmpty () {AfxMessageBox (_ T ("Please select a database! "); Return;} // if (m_pConnection-> GetState () // error: if the object is not created, GetStateif (m_pConnection! = NULL) {if (m_pConnection-> GetState () AfxMessageBox (_ T ("the database is connected! "); ElseAfxMessageBox (_ T (" the data connection object has been created, but the database is not connected successfully! "); Return;} try {HRESULT hr; // hr = m_pConnection.CreateInstance (" ADODB. connection "); // okhr = m_pConnection.CreateInstance (_ uuidof (Connection); if (SUCCEEDED (hr) {CString strConnection = _ T (" Provider = 'Microsoft. jet. OLEDB.4.0 '; Data Source =' "); strConnection + = m_strMdbPath; strConnection + =" '"; _ bstr_t bstrConnection = (LPTSTR) (LPCTSTR) strConnection; m_pConnection-> ConnectionTimeout = 10; // set the connection time m_pConn Ection-> Open (bstrConnection, "", "", adModeUnknown); AfxMessageBox (_ T ("connection successful! ") ;}} Catch (_ com_error & e) {AfxMessageBox (e. Description ());}}


Note:
1. m_pConnection.CreateInstance (_ uuidof (Connection); Use the. Operator instead of->. Although m_pConnection is a pointer, CreateInstance is a function of the pointer rather than a function of the object to which the Pointer Points.
2. m_pConnection! = Null does not indicate that the database is connected.


5. Disconnect the database

Void CMyAdoDlg: OnBnClickedDisconnect () {// TODO: add the control notification handler code here if (m_pConnection = NULL) {AfxMessageBox (_ T ("no database object instance is created! "); Return;} else if (! M_pConnection-> GetState () {AfxMessageBox (_ T ("the database object instance has been created, but the database is not connected! "); Return;} try {m_pConnection-> Close ();/* m_pConnection-> Release (); */m_pConnection = NULL; // The above release is not called, because the overloaded operator = will call Release:/* template <> _ com_ptr_t & operator = (Interface * pInterface) throw () {if (m_pInterface! = PInterface) {Interface * pOldInterface = m_pInterface; m_pInterface = pInterface; _ AddRef (); if (pOldInterface! = NULL) {pOldInterface-> Release () ;}} return * this;} */AfxMessageBox (_ T ("database disconnected successfully! ");} Catch (_ com_error & e) {AfxMessageBox (e. Description ());}}

Note:
1,
/* M_pConnection-> Release ();*/
M_pConnection = NULL;
Let these two statements be called by colleagues. During debugging, there is always an interruption, because the = is reloaded, And the reloaded functions call Release ()



6. SQL statement execution

/* SQL: create table employee (name nvarchar (20), sex text (1), age int); drop table employee; insert into employee values ('xinlang ', 'male', 24); insert into employee values ('ximei', 'female ', 25); select * from employee; */void CMyAdoDlg: OnBnClickedExcute () {// TODO: add the control notification handler code UpdateData () here; if (m_strSQL.IsEmpty () {AfxMessageBox (_ T ("fill in the SQL statement! "); Return;} if (m_pConnection = NULL |! M_pConnection-> GetState () {AfxMessageBox (_ T ("connect to the database! "); Return;} if (m_pRecordset! = NULL) {if (m_pRecordset-> GetState () m_pRecordset-> Close ();/* m_pRecordset-> Release (); */m_pRecordset = NULL ;} try {HRESULT hr; hr = m_pRecordset.CreateInstance ("adodb. recordset "); if (reverse (hr) {m_pRecordset-> Open (_ bstr_t (m_strSQL), _ variant_t (IDispatch *) m_pConnection), adOpenDynamic, adLockOptimistic, adw.text ); // If an SQL statement executes insert into, delete, and other operations that do not return record sets, m_pRecordset is disabled after the open statement is executed. // then, m_pRecordset is used to execute the operation, The system will prompt "the operation is not allowed when the object is closed !", If m_pRecordset executes select, // after execution, m_pRecordset is not closed. Therefore, you can execute the save operation // m_strSQL.MakeUpper (); // if (-1! = M_strSQL.Find (_ T ("SELECT") if (m_pRecordset-> GetState () {_ variant_t vtSave; _ bstr_t bstr; CString strSaveFilePath = GetSavefilePath (); savefileHandle (strSaveFilePath); m_xmlDlg.SetXmlFilePath (strSaveFilePath); bstr = strSaveFilePath; vtSave. vt = VT_BSTR; vtSave. bstrVal = bstr. copy (); // void PutCollect (const _ variant_t & Index, const _ variant_t & pvar); // m_pRecordset-> PutCollect ("name", _ bstr_t ("bytes I "); // remarks: used to modify the information of the current record // m_pRecordset-> PutCollect (" sex ", _ bstr_t (" medium ")); /// m_pRecordset-> MoveLast (); // m_pRecordset-> PutCollect ("name", _ bstr_t ("nihao"); // remarks: used to modify the information of the current record. // m_pRecordset-> PutCollect ("age", _ bstr_t ("100"); // inline HRESULT _ Recordset :: save (const _ variant_t & Destination, enum PersistFormatEnum PersistFormat) m_pRecordset-> Save (vtSave, adPersistXML); // Save the obtained information to vtSaveint state = m_pReco Rdset-> GetState (); while (! M_pRecordset-> ADOEOF) {_ variant_t vr; // vr. vt = VT_LPSTR; // the error message returned when the value assignment fails. // _ variant_t GetCollect (const _ variant_t & Index); // vr = m_pRecordset-> GetCollect ("name "); // OK // vr = m_pRecordset-> GetCollect ("sex"); // okvr = m_pRecordset-> GetCollect ("age"); m_pRecordset-> MoveNext ();}} else {AfxMessageBox (_ T ("SQL Execution successful! ") ;}} Catch (_ com_error & e) {AfxMessageBox (e. Description ());}}
7. Process stored files (saved as XML)
// Obtain the path of the saved file CString CMyAdoDlg: GetSavefilePath () {CString strSaveFile; if (! M_strMdbPath.IsEmpty () {strSaveFile = m_strMdbPath; strSaveFile = strSaveFile. left (1 + strSaveFile. reverseFind ('\'); strSaveFile + = DEFAULT_SAVE_XML_NAME;} return strSaveFile;} // process saved files BOOL CMyAdoDlg: SavefileHandle (CString & strSaveFilePath) {if (PathFileExists (strSaveFilePath) {CString strNewFile = strSaveFilePath; strNewFile + = _ T (". bak "); if (PathFileExists (strNewFile) DeleteFile (strNewFile); CFile: Rename (strSaveFilePath, strNewFile);} return TRUE ;}

#define DEFAULT_MDB_NAME _T("shujuku.mdb")#define DEFAULT_SAVE_XML_NAME _T("SaveData.xml")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.