In MFC, there are two main methods to connect to the SQL database.
1. Connect using ADO:
# Import "msado15.dll" no_namespace Rename ("EOF", "endoffile ")
// This dll must be imported. This file is usually stored in the C:/program files/common files/system/ADO path.
_ Connectionptr m_ptrconnection; // database connection object
Add the following statement to the constructor:
M_ptrconnection = NULL;
: Coinitialize (null );
// Main code for connecting to the database
Bool datavisitor: connectdatabase (_ bstr_t connectionstr)
{
/*
Added by stone. If idoconnection has not been set up, then create one.
*/
If (m_ptrconnection = NULL)
{
Hresult hR = m_ptrconnection.createinstance (_ uuidof (connection ));
If (failed (HR ))
{
Return false;
}
Else
{
_ Bstr_t strconnect = connectionstr;
// "Provider = sqloledb; server = (local); database = navigation; uid = sa; Pwd = 3277625 ;";
M_ptrconnection-> cursorlocation = aduseclient;
M_ptrconnection-> isolationlevel = adxactreadcommitted;
Try
{
M_ptrconnection-> open (strconnect, "", "", admodeunknown );
Return true;
}
Catch (_ com_error E)
{
// Afxmessagebox (char *) E. Description ());
Return false;
}
}
}
Return true;
}
2. Use ODBC to connect
# Include <afxdao. h>
Cdaodatabase * mydatabase;
Bool mydb_opersql: open_mydatabase (cstring connstr)
{
Try
{
If (mydatabase = NULL)
{
Mydatabase = new cdaodatabase ();
}
Mydatabase-> open (null, 0, 0, connstr );
}
Catch (cdaoexception * E)
{
Cstring message = _ T ("mydb_opersql database exception :");
Message + = e-> m_perrorinfo-> m_strdescription;
Char info [400];
Sprintf (Info, message );
Disperrormessage (Info ,__ line __);
E-> Delete ();
Return false;
}
Catch (cmemoryexception * E)
{
Disperrormessage ("mydb_opersql Memory exception! ",__ Line __);
E-> Delete ();
Return false;
}
Catch (...)
{
Disperrormessage ("mydb_opersql other exceptions! ",__ Line __);
Return false;
}
Return true;
}
The connection string connstr is generally the following content:
"ODBC; driver = {SQL Server}; server = (local); database = yourdatabase; uid = yourid; Pwd = yourpassword"