You can use C # To dynamically create an ODBC data source in two ways. Here I use the commonly used SQL2000 as an example.
Method 1: directly operate the registry and reference the Microsoft. Win32 namespace
/// <Summary>
/// Create an SQL data source
/// </Summary>
/// <Param name = "DNS"> data source name </param>
/// <Param name = "server"> server </param>
/// <Param name = "Database"> database </param>
/// <Returns> </returns>
Private bool createsqlodbc (string DSN, string server, string database)
{
Try
{
Registrykey regkey = registry. localmachine. opensubkey ("software"). opensubkey ("ODBC"). opensubkey ("ODBC. ini", true). createsubkey (DSN );
Regkey. setvalue ("driver", @ "C: \ windows \ system32 \ sqlsrv32.dll ");
Regkey. setvalue ("server", server );
Regkey. setvalue ("Database", database );
Regkey = registry. localmachine. opensubkey ("software"). opensubkey ("ODBC"). opensubkey ("ODBC. ini", true). opensubkey (
"ODBC Data Sources", true );
Regkey. setvalue (DNS, "SQL Server ");
Return true;
}
Catch
{
Return false;
}
}
Method 2: when using P/invoke (called by the Platform), the system. runtime. interopservices namespace must be referenced. The specific function parameter msdn has a more detailed explanation.
[Dllimport ("odbccp32.dll")]
Public static extern int sqlconfigdatasource (intptr hwndparent, int frequest, string lpszdriver, string lpszattributes );
Private int createsqlodbc (string DSN, string description, string server, string database)
{
String lpszattributes = string. empty;
Lpszattributes + = string. Format ("DSN = {0} \ 0", DSN );
Lpszattributes + = string. Format ("Description = {0} \ 0", description );
Lpszattributes + = string. Format ("Server = {0} \ 0", server );
Lpszattributes + = string. Format ("database = {0} \ 0", database );
Return sqlconfigdatasource (intptr) 0, 4, "SQL Server", lpszattributes );
}
Create another type of ODBC data source and change the corresponding driver and registry key.