c++封装odbc类

  1. //DBUtil.h  
  2. //By 小E QQ592646022  
  3. #include <windows.h>  
  4. #include <iostream>  
  5. #include <sql.h>  
  6. #include <sqlext.h>  
  7. #include <vector>  
  8. #include <string>  
  9. using namespace std;  
  10.    
  11. class ODBC  
  12. {  
  13. private:  
  14.     SQLHANDLE hEnv;  
  15.     SQLHANDLE hDbc;  
  16.     SQLHANDLE hStmt;  
  17.     SQLRETURN retCode;  
  18.     SQLINTEGER retErro;  
  19.     SQLINTEGER rowCount;  
  20.     SQLSMALLINT colCount;  
  21.     bool bState;  
  22.     char* pszUName;  
  23.     char* pszUPassword;  
  24.     char* pszDSN;  
  25. public:  
  26.     ODBC();  
  27.     ~ODBC();  
  28.     bool Connect();  
  29.     bool Close();  
  30.     bool IsOpen();  
  31.     int GetRowCount(){return rowCount;}  
  32.     int GetColCount(){return colCount;}  
  33.     vector<string*> ExecuteQueryVector(const char* pszSql);  
  34.     int ExecuteQuery(const char* pszSql);  //执行查询  
  35.     int ExecuteNonQuery(const char* pszSql);//执行非查询(更新或删除)  
  36.     int ExecuteUpdate(const char* pszSql);  //执行更新  
  37. };  
  38.    
  39. ODBC::ODBC()  
  40. {  
  41.     bState=false;  
  42.     rowCount=colCount=0;  
  43.     retCode=SQLAllocHandle(SQL_HANDLE_ENV,NULL,&hEnv);  
  44.     if((retCode!=SQL_SUCCESS)&& (retCode != SQL_SUCCESS_WITH_INFO))  
  45.     {  
  46.        cout<<"Erro AllocHandle"<<retCode<<endl;  
  47.        return;  
  48.     }  
  49.     retCode=SQLSetEnvAttr(hEnv,SQL_ATTR_ODBC_VERSION,(SQLPOINTER) SQL_OV_ODBC3,SQL_IS_INTEGER);  
  50.     if((retCode!=SQL_SUCCESS)&& (retCode != SQL_SUCCESS_WITH_INFO))  
  51.     {  
  52.        cout<<"Erro AllocHandle"<<retCode<<endl;  
  53.        SQLFreeHandle( SQL_HANDLE_DBC, hEnv );  
  54.        return;  
  55.     }  
  56.     retCode=SQLAllocHandle(SQL_HANDLE_DBC,hEnv,&hDbc);  
  57.     if((retCode!=SQL_SUCCESS)&& (retCode != SQL_SUCCESS_WITH_INFO))  
  58.     {  
  59.        cout<<"Erro AllocHandle"<<retCode<<endl;  
  60.        SQLFreeHandle( SQL_HANDLE_DBC, hEnv );  
  61.        return;  
  62.     }  
  63.     pszUName="sa";       //用户名  
  64.     pszUPassword="cty";  //密码  
  65.     pszDSN="QQ";         //数据源名  
  66.      
  67.    
  68. }  
  69. ODBC::~ODBC()  
  70. {  
  71.     Close();  
  72. }  
  73. bool ODBC::Connect()  
  74. {  
  75.     if(bState==false)  
  76.     {  
  77.       retCode=SQLConnect(hDbc,(SQLCHAR*) pszDSN,SQL_NTS,(SQLCHAR*) pszUName,SQL_NTS,(SQLCHAR*) pszUPassword,SQL_NTS);  
  78.        if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO))  
  79.        {  
  80.            cout<<"Erro Connect "<<retCode<<endl;  
  81.            SQLFreeHandle( SQL_HANDLE_DBC, hDbc );  
  82.            return false;  
  83.        }  
  84.        retCode=SQLAllocHandle(SQL_HANDLE_STMT,hDbc,&hStmt);  
  85.        if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO))  
  86.        {  
  87.            cout<<"Erro Connect "<<retCode<<endl;  
  88.            SQLDisconnect( hDbc );  
  89.            SQLFreeHandle( SQL_HANDLE_DBC, hDbc);  
  90.            return false;  
  91.        }  
  92.     }       
  93.     bState=true;  
  94.     cout<<"success!"<<endl;  
  95.     return true;  
  96.      
  97. }  
  98. int ODBC::ExecuteQuery(const char* pszSql)  
  99. {  
  100.      
  101.     if(pszSql==NULL)  
  102.        return 0;  
  103.     cout<<"hStmt="<<hStmt<<endl;  
  104.     retCode=SQLExecDirect(hStmt,(SQLCHAR*)pszSql,SQL_NTS);  
  105.     if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO))  
  106.     {  
  107.        cout<<"Erro ExecDirect "<<retCode<<endl;  
  108.        return -1;  
  109.     }  
  110. /*  retCode=SQLRowCount(hStmt,&rowCount);  //不受select 影响。。 
  111.     if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO)) 
  112.     { 
  113.        cout<<"Erro RowCount "<<retCode<<endl; 
  114.        return -1; 
  115.     }*/  
  116.     retCode=SQLNumResultCols(hStmt,&colCount);  
  117.     if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO))  
  118.     {  
  119.        cout<<"Erro ColCount "<<retCode<<endl;  
  120.        return -1;  
  121.     }  
  122.     rowCount=0;  
  123.     while(SQL_NO_DATA!=SQLFetch(hStmt))  
  124.     {  
  125.        //cout<<pszBuf<<endl;  
  126.        rowCount++;  
  127.     }  
  128.     SQLCancel(hStmt);  
  129.     return rowCount;  
  130. }  
  131. int ODBC::ExecuteNonQuery(const char* pszSql)  
  132. {  
  133.     rowCount=0;  
  134.     if(pszSql==NULL)  
  135.        return 0;  
  136.     //cout<<"hStmt="<<hStmt<<endl;  
  137.     retCode=SQLExecDirect(hStmt,(SQLCHAR*)pszSql,SQL_NTS);  
  138.     if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO))  
  139.     {  
  140.        cout<<"Erro ExecDirect "<<retCode<<endl;  
  141.        return -1;  
  142.     }  
  143.     retCode=SQLRowCount(hStmt,&rowCount);   
  144.     if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO))  
  145.     {  
  146.        cout<<"Erro RowCount "<<retCode<<endl;  
  147.        return -1;  
  148.     }  
  149.     retCode=SQLNumResultCols(hStmt,&colCount);  
  150.     if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO))  
  151.     {  
  152.        cout<<"Erro ColCount "<<retCode<<endl;  
  153.        return -1;  
  154.     }  
  155.      
  156.     SQLCancel(hStmt);  
  157.     return rowCount;  
  158. }  
  159. vector<string* >  ODBC::ExecuteQueryVector(const char* pszSql)  
  160. {  
  161.     vector<string* > v;  
  162.     if(pszSql==NULL)  
  163.        return 0;  
  164.     retCode=SQLExecDirect(hStmt,(SQLCHAR*)pszSql,SQL_NTS);  
  165.     if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO))  
  166.     {  
  167.        cout<<"Erro ExecDirect "<<retCode<<endl;  
  168.        return -1;  
  169.     }  
  170. /*  retCode=SQLRowCount(hStmt,&rowCount);  //不受select 影响。。 
  171.     if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO)) 
  172.     { 
  173.        cout<<"Erro RowCount "<<retCode<<endl; 
  174.        return -1; 
  175.     }*/  
  176.     retCode=SQLNumResultCols(hStmt,&colCount);  
  177.     if((retCode != SQL_SUCCESS) && (retCode != SQL_SUCCESS_WITH_INFO))  
  178.     {  
  179.        cout<<"Erro ColCount "<<retCode<<endl;  
  180.        return -1;  
  181.     }  
  182.     rowCount=0;  
  183.     SQLINTEGER colLen = 0;  
  184.     SQLSMALLINT buf_len = 0;  
  185.     SQLINTEGER colType = 0;  
  186.    
  187.     while(true)  
  188.     {    
  189.        char sz_buf[256];  
  190.        char* pszBuf;  
  191.        SQLINTEGER  buflen;  
  192.        string* rowData=new string[colCount+1];    
  193.        if(SQLFetch(hStmt)==SQL_NO_DATA)  
  194.        {  
  195.            break;  
  196.        }  
  197.        for(int i=1;i<=colCount;i++)  
  198.        {  
  199.            SQLColAttribute(hStmt, i, SQL_DESC_NAME, sz_buf, 256, &buf_len, 0);  
  200.            SQLColAttribute(hStmt, i, SQL_DESC_TYPE, 0, 0, 0, &colType);  
  201.            SQLColAttribute(hStmt, i, SQL_DESC_LENGTH, NULL, 0, 0, &colLen);  
  202.            pszBuf=new char[colLen+1];  
  203.            pszBuf[0]='/0';  
  204.            SQLGetData(hStmt,i,SQL_C_CHAR,pszBuf,50,&buflen);  
  205.            rowData[i-1]=pszBuf;  
  206.        }  
  207.        v.push_back(rowData);     
  208.        rowCount++;  
  209.        //cout<<"rowData[0]="<< (rowData[0])<<" rowData[1]="<<rowData[1]<<" rowData[2]="<<rowData[2]<<endl;;  
  210.     }  
  211.     SQLCancel(hStmt);  
  212.     return v;  
  213. }  
  214.    
  215. bool ODBC::Close()  
  216. {  
  217.     if(bState)  
  218.     {  
  219.        SQLDisconnect(hDbc);  
  220.        SQLFreeHandle(SQL_HANDLE_DBC,hDbc);  
  221.        SQLFreeHandle(SQL_HANDLE_ENV,hEnv);  
  222.        bState=false;  
  223.     }  
  224.    
  225.     return true;  
  226. }  
  227. bool ODBC::IsOpen()  
  228. {  
  229.     return bState;  
  230. }  
  231.    
  232. //Main.cpp 测试用 需要自行添加数据源 在odbc里面  
  233. #include <iostream>  
  234. #include "DBUtil.h"  
  235. #include <string.h>  
  236.    
  237. using namespace std;  
  238. int main()  
  239. {  
  240.     ODBC odbc;  
  241.     odbc.Connect();    
  242.     vector<string* > vv=odbc.ExecuteQueryVector("select * from users");  
  243.     vector<string* >::iterator it;  
  244.     for(it=vv.begin();it!=vv.end();it++)  
  245.     {  
  246.        for(int i=0;i<odbc.GetColCount();i++)  
  247.        {  
  248.            cout<<(*it)[i]<<" ";  
  249.        }  
  250.        cout<<(*it)[6]<<" "<<endl;  
  251.     }  
  252.     //odbc.ExecuteNonQuery("insert into users values('1','abcd',34,'男','2010-8-9','')");  
  253.     cout<<odbc.ExecuteNonQuery("delete from users where ID='10017'");  
  254.     return 0;  
  255. }
原文地址:http://blog.csdn.net/evilbinary_root/article/details/6358469
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然,这里是一个简单的示例,展示了如何使用C++封装ODBC的工具: ```cpp #include <iostream> #include <sql.h> #include <sqlext.h> class ODBCWrapper { public: ODBCWrapper(); ~ODBCWrapper(); bool Connect(const std::string& connectionString); bool Disconnect(); bool Execute(const std::string& query); bool Fetch(); int GetInt(int column); std::string GetString(int column); private: SQLHENV m_env; SQLHDBC m_conn; SQLHSTMT m_stmt; }; ODBCWrapper::ODBCWrapper() : m_env(nullptr), m_conn(nullptr), m_stmt(nullptr) { SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_env); SQLSetEnvAttr(m_env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0); SQLAllocHandle(SQL_HANDLE_DBC, m_env, &m_conn); } ODBCWrapper::~ODBCWrapper() { Disconnect(); SQLFreeHandle(SQL_HANDLE_DBC, m_conn); SQLFreeHandle(SQL_HANDLE_ENV, m_env); } bool ODBCWrapper::Connect(const std::string& connectionString) { SQLCHAR connStrOutput[256]; SQLSMALLINT connStrOutputSize; SQLDriverConnect(m_conn, NULL, (SQLCHAR*)connectionString.c_str(), SQL_NTS, connStrOutput, sizeof(connStrOutput), &connStrOutputSize, SQL_DRIVER_COMPLETE); if (SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_STMT, m_conn, &m_stmt))) { return true; } return false; } bool ODBCWrapper::Disconnect() { if (m_stmt != nullptr) { SQLFreeHandle(SQL_HANDLE_STMT, m_stmt); m_stmt = nullptr; } if (m_conn != nullptr) { SQLDisconnect(m_conn); return SQL_SUCCEEDED(SQLFreeHandle(SQL_HANDLE_DBC, m_conn)); } return false; } bool ODBCWrapper::Execute(const std::string& query) { if (SQL_SUCCEEDED(SQLExecDirect(m_stmt, (SQLCHAR*)query.c_str(), SQL_NTS))) { return true; } return false; } bool ODBCWrapper::Fetch() { if (SQL_SUCCEEDED(SQLFetch(m_stmt))) { return true; } return false; } int ODBCWrapper::GetInt(int column) { int value; SQLGetData(m_stmt, column, SQL_C_SLONG, &value, sizeof(value), nullptr); return value; } std::string ODBCWrapper::GetString(int column) { SQLCHAR value[256]; SQLLEN indicator; SQLGetData(m_stmt, column, SQL_C_CHAR, value, sizeof(value), &indicator); return std::string((const char*)value); } int main() { ODBCWrapper odbc; if (odbc.Connect("DRIVER={SQL Server};SERVER=localhost;DATABASE=mydatabase;UID=myusername;PWD=mypassword")) { if (odbc.Execute("SELECT * FROM mytable")) { while (odbc.Fetch()) { int id = odbc.GetInt(1); std::string name = odbc.GetString(2); std::cout << "ID: " << id << ", Name: " << name << std::endl; } } odbc.Disconnect(); } return 0; } ``` 这个示例展示了一个简单的ODBC封装工具`ODBCWrapper`,它使用ODBC API来连接数据库、执行查询语句并获取结果。你可以根据自己的需要进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值