在.NET中打开ODBC“选择数据源”对话框
在VB和C++中,都有相应的函数来打开ODBC的“选择数据源”对话框,且简单方便。
年轻气盛的.Net,偏偏抛弃了这个对话框;在类库中百复千转,就是没有找到。无奈之下,自己动手。真是信天信地不如信自己,连MS都不能信了,你说还能信谁呢?:) 权衡一翻后,选择了用VC开发一个小COM,在.NET中拉使用。
ODBC API中有 SQLDriverConnect,即是显示“选择数据源”对话框的。代码非常简单,不过十多行,与同好共享:
#ifdef UNICODE
#define MYSQLCHAR SQLWCHAR
#else
#define MYSQLCHAR SQLCHAR
#endif
STDMETHODIMP CODBCSourceSelector::Open( OLE_HANDLE hwnd, BSTR *connectionString)
{
CComBSTR bstrConnectionString;
MYSQLCHAR szConnectOutput[MAX_CONNECT_LEN];
memset( szConnectOutput, 0, sizeof( szConnectOutput ) * sizeof( UCHAR ) );
SQLHDBC hdbc = SQL_NULL_HANDLE;
SQLHENV henv = SQL_NULL_HANDLE;
SQLRETURN ret;
ret = SQLAllocEnv( &henv );
if ( SQL_SUCCESS == ret || SQL_SUCCESS_WITH_INFO == ret )
{
ret = SQLAllocConnect( henv, &hdbc );
}
if ( SQL_SUCCESS == ret || SQL_SUCCESS_WITH_INFO == ret )
{
HWND realWnd = (HWND)hwnd;
if ( !realWnd )
{
realWnd = ::GetDesktopWindow();
}
SQLSMALLINT cbConnStrOut = 0;
ret = SQLDriverConnect( hdbc, realWnd,
(MYSQLCHAR*)NULL, 0,
szConnectOutput, _countof(szConnectOutput),
&cbConnStrOut, 3 );
if ( SQL_SUCCESS==ret || SQL_SUCCESS_WITH_INFO==ret )
{
bstrConnectionString = (TCHAR*)szConnectOutput;
SQLDisconnect( hdbc );
}
}
SQLFreeConnect( hdbc );
SQLFreeEnv( henv );
*connectionString = bstrConnectionString.Detach();
return S_OK;
}
#define MYSQLCHAR SQLWCHAR
#else
#define MYSQLCHAR SQLCHAR
#endif
STDMETHODIMP CODBCSourceSelector::Open( OLE_HANDLE hwnd, BSTR *connectionString)
{
CComBSTR bstrConnectionString;
MYSQLCHAR szConnectOutput[MAX_CONNECT_LEN];
memset( szConnectOutput, 0, sizeof( szConnectOutput ) * sizeof( UCHAR ) );
SQLHDBC hdbc = SQL_NULL_HANDLE;
SQLHENV henv = SQL_NULL_HANDLE;
SQLRETURN ret;
ret = SQLAllocEnv( &henv );
if ( SQL_SUCCESS == ret || SQL_SUCCESS_WITH_INFO == ret )
{
ret = SQLAllocConnect( henv, &hdbc );
}
if ( SQL_SUCCESS == ret || SQL_SUCCESS_WITH_INFO == ret )
{
HWND realWnd = (HWND)hwnd;
if ( !realWnd )
{
realWnd = ::GetDesktopWindow();
}
SQLSMALLINT cbConnStrOut = 0;
ret = SQLDriverConnect( hdbc, realWnd,
(MYSQLCHAR*)NULL, 0,
szConnectOutput, _countof(szConnectOutput),
&cbConnStrOut, 3 );
if ( SQL_SUCCESS==ret || SQL_SUCCESS_WITH_INFO==ret )
{
bstrConnectionString = (TCHAR*)szConnectOutput;
SQLDisconnect( hdbc );
}
}
SQLFreeConnect( hdbc );
SQLFreeEnv( henv );
*connectionString = bstrConnectionString.Detach();
return S_OK;
}
整个 project 下载:https://files.cnblogs.com/dumack/ODBCSource.zip