C # dynamically create an ODBC Data Source

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.