Accessing a database using ADO in MFC

Source: Internet
Author: User
I personally think that the database operation connection and operations get started quickly, but those types will always make you a headache at present I have not figured out how to use the decimal technology from the T-SQL to the appropriate data in MFC ?? Step 1 of database connection: load the dynamic link library # importC: ProgramFilesCommonFilesSystemADOmsado15.dllno

I personally think that the database operation connection and operations get started quickly, but those types will always make you a headache at present I have not figured out how to use the decimal technology from the T-SQL to the appropriate data in MFC ?? Step 1 of database connection: load the dynamic link library # import C: \ Program Files \ Common Files \ System \ ADO \ msado15.dll \ no

I personally think that database operation connections and operations are quick to use, but those types will always give you a headache

At present, I have not figured out how to use the decimal Technology of T-SQL to the corresponding data in MFC ??


Perform the following steps to connect to the database:


I. Load the dynamic link library

# Import "C: \ Program Files \ Common Files \ System \ ADO \ msado15.dll "\
No_namespace rename ("EOF", "EndOfFile ")

What does this sentence mean? import the dynamic link library. Otherwise, all your ptrConn and ptrRecord connection pointers will report errors during compilation.

Replace the second rename and EOF with EndOfFile to determine whether the end is reached when the Recordset is retrieved from the Recordset.

If the end is reached, non-VARIANT_FALSE is returned.


2. Declare the connection pointer and record set

_ ConnectionPtr ptrConn; // defines the Connection object.
_ RecordsetPtr ptrRecord;

3. Create a connection

CoInitialize (NULL); // do not forget; otherwise, all pointers are NULL and invalid.

Try // open the connection {// create a connection object ptrConn. createInstance (_ uuidof (Connection); // sets the maximum number of seconds for the Connection to wait. The default value is 15 seconds ptrConn-> ConnectionTimeout = 20; // Open the connection ptrConn-> Open ("driver = {SQL server}; server = 127.0.0.1; uid = laicb; pwd = 616458; database = DBCourse ","", // login username "", // login password adConnectUnspecified); // open connection} catch (_ com_error & e) -- catch exception {CString str; CString strTemp; str. format (TEXT ("Error: \ n"); strTemp. format (TEXT ("Code = % 08lx \ n"), e. error (); str + = "\ n"; str + = strTemp; strTemp. format (TEXT ("Meaning = % s \ n"), e. errorMessage (); str + = "\ n"; str + = strTemp; strTemp. format (TEXT ("Source = % s \ n"), (wchar_t *) e. source (); str + = "\ n"; str + = strTemp; strTemp. format (TEXT ("Description = % s \ n"), (wchar_t *) e. description (); str + = "\ n"; str + = strTemp; MessageBox (str );}
4. Open the record set and initialize the record set

Try {// _ RecordsetPtr ptrRS; // recordset object // create recordset object ptrRecord. createInstance (_ uuidof (Recordset); // in some cases, if you have used record-level backend, you may need to recreate the instance, then Open ptrRecord-> Open ("select * from dbo. staffInfo ", // Why do I change the database here to dbo. when StaffRecord is set, the list box displays all empty ptrConn. getInterfacePtr (), adOpenKeyset, // note that in the VB instruction document, the first letter a is in upper case, and the lower-case adLockBatchOptimistic and adshorttext must be in C ++ ); // int j = ptrRecord-> RecordCount; // or // ptrRS = ptrConn-> Execute (m _ strSql, NULL, ad1_text);} catch (_ com_error & e) {CString str; CString strTemp; str. format (TEXT ("Error: \ n"); strTemp. format (TEXT ("Code = % 08lx \ n"), e. error (); str + = "\ n"; str + = strTemp; strTemp. format (TEXT ("Meaning = % s \ n"), e. errorMessage (); str + = "\ n"; str + = strTemp; strTemp. format (TEXT ("Source = % s \ n"), (wchar_t *) e. source (); str + = "\ n"; str + = strTemp; strTemp. format (TEXT ("Description = % s \ n"), (wchar_t *) e. description (); str + = "\ n"; str + = strTemp; MessageBox (str );}
5. Execute the statement

Try {ptrConn-> Execute ("select * from dbo. login ", NULL, ad1_text); ptrRecord-> MoveFirst (); // This statement can be used to retrieve data, it may be that the last parent pointer has moved it to the last int I = ptrRecord-> RecordCount; // if you move the cursor from dynamic to record set, this parameter is useful when (ptrRecord-> EndOfFile = VARIANT_FALSE) {_ variant_t va; _ variant_t str; va. vt = VT_I4; va. lVal = 0; str = ptrRecord-> Fields-> GetItem (va)-> Value; CString strGetID (wchar_t *) (_ bstr_t) str ); str = ptrRecord-> Fields-> GetItem (short (1)-> Value; CString strGetSerect (wchar_t *) (_ bstr_t) str); strGetID. trimRight (); strGetSerect. trimRight (); right = ptrRecord-> Fields-> GetItem (short (2)-> Value. intVal; if (strGetID = strID & strGetSerect = strSerect) {isadmin = true;} ptrRecord-> MoveNext () ;}} catch (_ com_error & e) {CString str; CString strTemp; str. format (TEXT ("Error: \ n"); strTemp. format (TEXT ("Code = % 08lx \ n"), e. error (); str + = "\ n"; str + = strTemp; strTemp. format (TEXT ("Meaning = % s \ n"), e. errorMessage (); str + = "\ n"; str + = strTemp; strTemp. format (TEXT ("Source = % s \ n"), (wchar_t *) e. source (); str + = "\ n"; str + = strTemp; strTemp. format (TEXT ("Description = % s \ n"), (wchar_t *) e. description (); str + = "\ n"; str + = strTemp; AfxMessageBox (str );}
Connection: Execute to Execute the SQL statement. If any result is returned, Recordset is returned. If no result is returned, it can be directly executed.

The query result is

 ptrRecord->Fields->GetItem(va)->Value;
 ptrRecord->Fields->GetItem(va)->Name;
Va is
_variant_t va;va.vt=VT_I4;va.lVal=0;
You can also
 ptrRecord->Fields->GetItem(short(0))->Name;
The returned result is
while(ptrRecord->EndOfFile==VARIANT_FALSE)
Retrieve result set
ptrRecord->MoveNext();
Sometimes, if all your result sets have been obtained, that is, your result set has reached non-VARIANT_FALSE.
At this time, you need to re-create the instance and then open,
PtrRecord. createInstance (_ uuidof (Recordset); // in some cases, if you have used record-level backend, you may need to recreate the instance, then Open ptrRecord-> Open ("select * from dbo. staffInfo ", // Why do I change the database here to dbo. when StaffRecord is set, the list box displays all empty ptrConn. getInterfacePtr (), adOpenKeyset, // note that in the VB instruction document, the first letter a is in upper case, and the lower-case adLockBatchOptimistic and adshorttext must be in C ++ );
So that you can use it again. Otherwise, it seems like MoveFirst. Is it useful?
In addition, if you call close somewhere in the result set, you must execute the preceding statement when you use it again. Otherwise, it will report that the record set is closed and wufa uses

Vi. Use of Command objects

Try
{
// Create Connection Object (1.5 Version)
Conn1.CreateInstance (_ uuidof (Connection ));
Conn1-> ConnectionString = bstrConnect;
Conn1-> Open (bstrEmpty,-1 );
// Create Command Object
Statement 1.createinstance (_ uuidof (Command ));
Cmd1-> ActiveConnection = Conn1;
Cmd1-> CommandText = _ bstr_t ("SELECT * FROM mytable WHERE age <? ");

Then Execute the command. Then you can Execute the command cmd1> Execute.


End:

Some release operations and empty operations


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.