写注册表动态创建SQL Server ODBC数据源
各个参数的意义:
DBServer: 数据库所在主机
DBName: 数据库名称
DSN: 数据源名称
UID: 登陆用户
返回值:
-1: 没有安装SQL Server驱动程序
-2: 其他错误
0: 成功
实现函数:
int MakeSQLServerODBCDSN(LPCTSTR DBServer,LPCTSTR DBName,LPCTSTR DSN,LPCTSTR UID)
{
BOOL bInstallDriver=TRUE;
CRegKey regKey;
LONG lRet=regKey.Open(HKEY_LOCAL_MACHINE,"Software//ODBC//ODBCINST.INI//SQL Server");
if(lRet!=ERROR_SUCCESS)
{
bInstallDriver=FALSE;
}
else
{
char szDirverPath[MAX_PATH]="";
DWORD dwCount=100;
lRet=regKey.QueryValue(szDirverPath,"Driver",&dwCount);
if((lRet!=ERROR_SUCCESS)||(dwCount<1))
{
DWORD dwErr=GetLastError();
bInstallDriver=FALSE;
}
regKey.Close();
}
if(!bInstallDriver)
{
return -1;
}
CString strKeyValueName="Software//ODBC//ODBC.INI//";
strKeyValueName+=DSN;
lRet=regKey.Create(HKEY_LOCAL_MACHINE,strKeyValueName);
if(lRet!=ERROR_SUCCESS)
{
return -2;
}
regKey.SetValue(DBName,"Database");
regKey.SetValue("SQLSrv32.dll","Driver");
regKey.SetValue(DBServer,"Server");
regKey.SetValue(UID,"LastUser");
regKey.m_hKey=HKEY_LOCAL_MACHINE;
regKey.SetKeyValue("Software//ODBC//ODBC.INI//ODBC Data Sources","SQL Server",DSN);
regKey.Close();
return 0;
}