当我们需要部署我们的应用时,有时候会需要手动添加或删除数据源。但是如果能够通过安装程序自动完成数据源的删除或者
添加,那将会显得更加人性化。通过程序修改数据源,一般有两种方法,一种是直接修改windows注册表,我们可以用windows API函数曾改HKEY_LOCAL_MACHINE/Software/ODBC/ODBC.INI中的键值;另一种是使用ODBC API来设置ODBC数据源。
需要使用到的动态连接库为ODBCCP32.DLL,api函数为SQLConfigDataSource(),该函数可以动态的增加,删除修改数据源。
下面的代码用C#实现了数据源的增加。
//导入ODBCCP32.DLL,声明函数(导入命名空间System.Runtime.InteropServices)
[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); //数据库名
lpszAttributes += "Trusted_Connection=Yes"; //windows认证
return SQLConfigDataSource((IntPtr)0, 4, "SQL Server", lpszAttributes);
}