使用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)0, 4, "SQL Server", lpszAttributes); }
創建其他類型的ODBC數據源更改相應的驅動和注冊表項即可。
