Editor's note: This article is the author of the recent release of an article to supplement, before reading this article, it is best to first look at the original article: "A perfect ODBC database program."
From a user-friendly perspective, you should use dynamic creation of the data source in your program. After the editor's reminder, I looked for some information, but fortunately finally achieved. The code is as follows:
int CMainFrame::OnCreate (lpcreatestruct lpcreatestruct) {if (cframewnd::oncreate (lpcreatestruct) = = 1) return-1;//
The path to the database (refer to Xu Jingzhou, read access file directly through DAO 〉cstring spath;
GetModuleFileName (Null,spath.getbuffersetlength (max_path+1), MAX_PATH);
Spath.releasebuffer ();
int NPOs;
Npos=spath.reversefind (' \ \ ');
Spath=spath.left (NPOs);
CString lpszfile = spath + "\\student.mdb";
When using the SQLConfigDataSource () function, there is a need to pay attention to, because in the function of the CString//variable, because itself is a string, and finally have the, so the following method to deal with: char* Szdesc;
int Mlen;
Szdesc=new char[256]; sprintf (Szdesc, "dsn=%s?") DESCRIPTION=TOC support source? Dbq=%s? Fil=microsoftaccess? defaultdir=%s??
"," not ", Lpszfile,spath); Not is the data source name you can change it.
But must be consistent with the data source name in the CString clhwyset::getdefaultconnect ()//{//Return _t ("Odbc;dsn=not");
Mlen = strlen (SZDESC);
for (int i=0; i<mlen; i++) {if (szdesc[i] = = '? ')
Szdesc[i] = ' '; //sqlconfigdatasource () Function usage Reference: Setting up an ODBC data source with Visual C + + program implementation The following//two usages are unsuccessful//if (False==sqlconFigdatasource (Null,odbc_add_dsn, "Microsoft Access Driver (*.mdb)", "dsn=abbdbq=lpszfiledefaultdir=spath\0"))//IF (Null,odbc_add_dsn, Microsoft Access Driver (*.mdb) False==sqlconfigdatasource, "dsn=abb\0dbq=lpszfile\ 0defaultdir=spath\0\0 ")) if (FALSE = = SQLConfigDataSource (null,odbc_add_dsn, Microsoft Access Driver (*.mdb)), (
LPCSTR) Szdesc)) AfxMessageBox ("Failed");
return 0; }
Two points to note:
1. You need to include header files at the beginning: #include <odbcinst.h>.
2. Student.mdb must be in the same directory as the Lhwy application.
You can also do a user from a dialog box to the program to enter the ODBC data source name, and through the file directory to select the desired database, try. But must pay attention to the CString processing method.