摘抄的一段使用ODBC API 连接数据库的代码 ps:msdn文档 http://msdn.microsoft.com/en-us/library/ms714562(VS.85).aspx头文件
SQLHENV m_henv; /**////< ODBC环境句柄 SQLHDBC m_hdbc; ///< ODBC句柄 SQLHSTMT m_hstmt; ///< ODBC游标句柄 char m_szDSN[256]; /**////< 数据源名 char m_szUserName[256]; ///< 用户名 char m_szPassword[256]; ///< 密码 BOOL m_bAutoCommit; ///< 是否自动提交
连接函数
BOOL CODBCTestDemo001Dlg::AllocHandle(SQLHENV &henv, SQLHDBC &hdbc, SQLHSTMT &hstmt) { SQLRETURN retcode;
retcode = SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&henv); if(retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { retcode = SQLSetEnvAttr(henv,SQL_ATTR_ODBC_VERSION,(void *)SQL_OV_ODBC3,0); if(retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { retcode = SQLAllocHandle(SQL_HANDLE_DBC,henv,&hdbc); if(retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { SQLSetConnectAttr(hdbc,(long)SQL_LOGIN_TIMEOUT,(void *)5,0); if(m_bAutoCommit) SQLSetConnectAttr(hdbc,(long)SQL_ATTR_AUTOCOMMIT,(void *)SQL_AUTOCOMMIT_ON,0); else SQLSetConnectAttr(hdbc,(long)SQL_ATTR_AUTOCOMMIT,(void *)SQL_AUTOCOMMIT_OFF,0); retcode = SQLConnect(hdbc,(SQLCHAR *)(LPTSTR)m_szDSN,SQL_NTS, (SQLCHAR *)(LPTSTR)m_szUserName,SQL_NTS,(SQLCHAR *)(LPTSTR)m_szPassword,SQL_NTS); if(retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { return TRUE; } else { //ShowError(SQL_HANDLE_DBC,hdbc); }
SQLFreeHandle(SQL_HANDLE_DBC,hdbc); hdbc = NULL; } else TRACE("It's Useless!"); //ShowError(SQL_HANDLE_ENV,henv); } else //ShowError(SQL_HANDLE_ENV,henv); SQLFreeHandle(SQL_HANDLE_ENV,henv); henv = NULL; } else return FALSE; return FALSE; }
关闭连接
void CODBCTestDemo001Dlg::DeAllocHandle(SQLHENV henv, SQLHDBC hdbc, SQLHSTMT hstmt) { if (m_hdbc) { SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC,hdbc); } if (m_henv) { SQLFreeHandle(SQL_HANDLE_ENV,henv); } }
|