惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
aimingoo的专栏
aimingoo的专栏
Martin Fowler
Martin Fowler
C
Check Point Blog
G
Google Developers Blog
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Google DeepMind News
Google DeepMind News
人人都是产品经理
人人都是产品经理
有赞技术团队
有赞技术团队
MongoDB | Blog
MongoDB | Blog
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
大猫的无限游戏
大猫的无限游戏
D
Docker
Hugging Face - Blog
Hugging Face - Blog
The GitHub Blog
The GitHub Blog
博客园 - 三生石上(FineUI控件)
A
About on SuperTechFans
Recent Announcements
Recent Announcements
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
Stack Overflow Blog
Stack Overflow Blog
Vercel News
Vercel News

博客园 - 费哥

VC++实现应用程序对插件的支持(转) typedef的四个用途和两个陷阱(转) 设为首页,加入收藏,联系我们 - 费哥 - 博客园 ASP.NET 2.0中CSS失效 ADO.NET更新ACCESS碰到的怪异问题 DataGrid中的數據輸出到Excel 对 Windows 窗体控件进行线程安全调用 将参数传递给线程(Vc#2005) 创建合理位置的线标注 Sql2005导出SQL2000格式的脚本 c#枚举的用法及遍历方法 将外部图块插入当前图形(c#代码) 无法将顶级控件添加到控件 使用Microsoft Visual Studio2005开发ObjectARX设置 CS1595:已在多处定义 软件设计师考试大纲 <<设计模式可复用面向对象软件的基础>>--组合模式(Composite) <<设计模式可复用面向对象软件的基础>>--设计模式怎样解决设计问题 <<设计模式可复用面向对象软件的基础>>读书笔记--(第一章)引言
c#动态创建ODBC数据源
费哥 · 2008-09-08 · via 博客园 - 费哥

使用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数据源更改相应的驱动和注册表项即可。