How do I create an ODBC DSN entry using C#?

前端 未结 7 1204
旧巷少年郎
旧巷少年郎 2020-11-29 23:43

I\'m working on a legacy application that has a C++ extended stored procedure. This xsproc uses ODBC to connect to the database, which means it requires a DSN to be config

相关标签:
7条回答
  • 2020-11-30 00:09

    Further to chrfalch's post, here is some sample code for updating a DSN (I know the OP is asking for creation, however this code is easily translatable to whatever you need to do) using the API call rather than via the registry direct (using the information from the pinvoke.net page):-

    [DllImport("ODBCCP32.DLL", CharSet = CharSet.Unicode, SetLastError = true)]
    static extern bool SQLConfigDataSourceW(UInt32 hwndParent, RequestFlags fRequest, string lpszDriver, string lpszAttributes);
    
    enum RequestFlags : int
    {
        ODBC_ADD_DSN = 1,
        ODBC_CONFIG_DSN = 2,
        ODBC_REMOVE_DSN = 3,
        ODBC_ADD_SYS_DSN = 4,
        ODBC_CONFIG_SYS_DSN = 5,
        ODBC_REMOVE_SYS_DSN = 6,
        ODBC_REMOVE_DEFAULT_DSN = 7
    }
    
    bool UpdateDsnServer(string name, string server)
    {
        var flag = RequestFlags.ODBC_CONFIG_SYS_DSN;
        string dsnNameLine = "DSN=" + name;
        string serverLine = "Server=" + server;
    
        string configString = new[] { dsnNameLine, serverLine }.Aggregate("", (str, line) => str + line + "\0");
    
        return SQLConfigDataSourceW(0, flag, "SQL Server", configString);
    }
    
    0 讨论(0)
提交回复
热议问题