The dynamic link library odbcinst. dll in the Windows system subdirectory provides a function sqlconfigdatasource () that can dynamically add, modify, and delete data sources (). The function is prototype as follows:
Bool sqlconfigdatasource (hwnd hwndparent, word frequest, lpcstr lpszdriver, lpcstr lpszattributes );
The hwndparent parameter is the parent window handle. If the value is null, the dialog box related to the parent window is not displayed.
The frequest parameter can be set to one of the following values:
Odbc_add_dsn: adds a new user data source;
Odbc_config_dsn: Modify (configure) an existing user data source;
Odbc_remove_dsn: delete an existing user data source;
Odbc_add_sys_dsn: Add a new system data source;
Odbc_config_sys_dsn: modifies (configures) an existing system data source;
Odbc_remove_sys_dsn: delete an existing system data source.
The lpszdriver parameter is used to pass the database engine name, which is equivalent to the strdbtype variable in method 1.
The lpszattirbutes parameter is the value of a keyword, that is, a series of "keyname = value" strings separated, for example, "DSN = demo/0dsn = demo/0 description = Sample Database ". For detailed settings of this parameter, see the help documentation of sqlconfigdatasource () function and various ODBC driver documentation in msdn.
Because the default library file of VC does not contain the sqlconfigdatasource () function, before using this function, you need. the H file is included in the header file of the project. In the settings Properties dialog box of the project, add odbccp32.lib to the object/library modules edit box on the Link property page, and ensure that the file odbccp32.dll is under system32.
OtherwiseThe following error occurs during link: Error lnk2001: unresolved external symbol._ Sqlconfigdatasource @ 16.
Take Microsoft Access as an example. Set the data source name to demo and the data source description to "Sample Data Source". Then, add the following code where the data source needs to be dynamically loaded:
: Sqlconfigdatasource (null, odbc_add_sys_dsn, "Microsoft Access Driver (*. mdb)", "DSN = demo/0 description = Sample Database ");
Note thatIn Microsoft Access Driver (*. mdb), there must be a space between "driver" and "(").Otherwise, the function call will fail. I spent more than half an hour debugging on this.