C# 操作ODBC數據源


新建

 

 

 

LocalMachine對應系統
CurrentUser對應使用者
 string strText= File.ReadAllText(@"C:\Windows\Eado.ini");            
            Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software").OpenSubKey("ODBC").
                OpenSubKey("ODBC.INI", true).DeleteSubKey(DsnName.Trim());
            //在HKEY_LOCAL_MACHINE/Software/ODBC/ODBC.INI中創建一個子鍵和相應的值
            Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software").
                OpenSubKey("ODBC").OpenSubKey("ODBC.INI", true).CreateSubKey(DsnName.Trim());
            regkey.SetValue("DataBase", "efoxsfcmu3seagate");
            regkey.SetValue("Driver", @"C:\WINDOWS\System32\SQLSRV32.dll");
            regkey.SetValue("Server", ServerName.Trim());
            regkey.SetValue("LastUser", "essnlxddl");
            regkey.SetValue("Trusted_Connection", "No");//如果是賬密登錄,
            //在HKEY_LOCAL_MACHINE/Software/ODBC/ODBC.INI/ODBC Data Sources中增加一個字符串鍵值
            regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software").OpenSubKey("ODBC")
                .OpenSubKey("ODBC.INI", true).OpenSubKey("ODBC Data Sources", true);
            regkey.SetValue(DsnName.Trim(), "SQL Server");
            return true;

localMachine

直接操作注冊表,需要引用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); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM