费哥的博客

心若在,梦就在
随笔 - 52, 文章 - 0, 评论 - 33, 引用 - 0
数据加载中……

c#动态创建ODBC数据源

使用C#有两种方法可以动态的创建ODBC数据源,这里我用比较常用的SQL2000作为例子。

 

方法1:直接操作注册表,需要引用Microsoft.Win32命名空间

 

/// <summary>

/// 创建SQL数据源
/// </summary>
/// <param name="dns">数据源名称</param>
/// <param name="server">服务器</param>
/// <param name="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;
     }
}

 

方法2:使用P/Invoke(平台调用),需要引用System.Runtime.InteropServices命名空间,具体的函数参数MSDN有比较详细的解释

[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)04"SQL Server", lpszAttributes);
}

 创建其他类型的ODBC数据源更改相应的驱动和注册表项即可。

 

posted on 2008-09-08 14:45 费哥 阅读(69) 评论(0)  编辑 收藏 网摘 所属分类: .net


标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-09-10 10:33 编辑过
Google站内搜索

相关文章:


相关搜索:
c# ODBC 数据源

相关链接: