(From "Visual C ++ database development basics and Applications" This book P196-197 section 7.2.3 database connection) When developing the mfc odbc database, you need to introduce the definition file afxdb of the mfc odbc database class. h, in the project stdafx. add the file using the include statement in the H file as follows: # Include <afxdb. h> Before establishing a database connection, you need to define a cdatabase object. The Code is as follows: cdatabase m_db; Use the openex function of the cdatabase class to establish a connection to the database. The function prototype is as follows: Virtual bool openex (lpctstr Lpszconnectstring, DWORD Dwoptions = 0 ); Throw (cdbexception, cmemoryexception ); Where,LpszconnectstringIs the ODBC connection string, which contains the data source name, user name, and user password. The format is "DSN = server_source; uid = 123; Pwd = ABC". DSN indicates the ODBC Data Source Name, uid indicates the database user name, And PWD indicates the database user password. For the misdb of the configured ODBC data source, the username and user password are the ODBC connection strings of dbattend in the format of "DSN = misdb; uid = dbattend; Pwd = dbattend ". The code for using the cdatabase openex function to establish a database connection is as follows: // Create a connection string Cstring strconnect; Strconnect. Format ("DSN = % s; uid = % s; Pwd = % s", "misdb", "dbattend", "dbattend "); // Open the database connection and catch exceptions Try { M_db.openex (strconnect, cdatabase: noodbcdialog ); } Catch (cdbexception, ex) // handle database exceptions { Afxmessagebix (ex-> m_strerror ); Afxmessagebix (ex-> m_strstatenativeorigin ); } And_catch (cmemoryexception, PEX) // handle memory exceptions { Pex-> reporterror (); Afxmessagebox ("Memory exception "); } And_catch (cexception, e) // handle other exceptions { Tchar szerror [100]; E-> geterrormessage (szerror, 100 ); Afxmessagebox (szerror ); } End_catch From the prototype of the openex function, we can see that the openex function may throw cdbexception and cmemoryexception, which must be handled. Many functions of the mfc odbc database class may encounter exceptions when calling. You can use exceptions such as try, catch, and_catch, and end_catch to process macro catch and handle these exceptions. Otherwise, when an exception occurs, the program will be terminated abnormally, causing inconvenience or even some loss to the user. |