zoukankan      html  css  js  c++  java
  • 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:WINDOWSsystem32SQLSRV32.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}",dsn);
    
                lpszAttributes += string.Format("DESCRIPTION={0}", description);
    
                lpszAttributes += string.Format("SERVER={0}", server);
    
                lpszAttributes += string.Format("DATABASE={0}", database);
    
                return SQLConfigDataSource((IntPtr)0, 4, "SQL Server", lpszAttributes);
    
    }

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

  • 相关阅读:
    Perl的运算符号字符
    windows xp 使用远程桌面时的关机/重新启动方法
    抵御TCP的洪水
    远程桌面连接中的常见问题 连接上就断开
    批量kill mysql进程
    Linux如何查看硬盘型号和缓存
    Apache Rewrite 规则详解
    nginx 内置变量大全
    大数据量分页存储过程效率测试附代码
    ASP.Net 更新页面输出缓存的几种方法(包括用户控件,iframe,页面缓存等)
  • 原文地址:https://www.cnblogs.com/blosaa/p/3150785.html
Copyright © 2011-2022 走看看