Encapsulation of unixodbc

Source: Internet
Author: User

This code can be reproduced and used at will, but keep the source

// Blog.csdn.net/bat603

// By Ben

//

//. H

/*
Author: lizp
MSN: lizp.net@gmail.com

URL: blog.csdn.net/bat603
Description: uses the tutorial on the unixodbc homepage to encapsulate unixodbc and adds the lock function, which is very convenient to use.

*/

# Ifndef _ cpp_odbc_h _
# DEFINE _ cpp_odbc_h _

# Include <stdlib. h>
# Include <stdio. h>
# Include <pthread. h>
# Include <SQL. h>
# Include <sqlext. h>
# Include <sqltypes. h>

// Maximum number of queried Fields
# Define field_num 1024

Class cppodbc
{
Public:
Cppodbc ();
Virtual ~ Cppodbc ();
// Public interface
Public:
Bool open ();
Bool close ();
Bool connect (const char * pszdsn, const char * pszuname, const char * pszupasswd );
Bool disconnect ();
Bool clear ();
Unsigned int sqlquery (const char * pszsql );
Unsigned int sqlexec (const char * pszsql );
Unsigned int sqlexecautoid (char * pszsql );
Bool isopen ();
// Number of query results. The number of updated records is returned during the update and the number of deleted records are returned during the deletion.
Unsigned int getcount ();
// Two columns are returned for the query result.
Unsigned int getcolumns ();
Int getintvalue (unsigned int uiindex );
Char * getstrvalue (unsigned int uiindex );
// Cancel the operation
Bool cancel ();
// Get error code
Unsigned int geterror ();
// Next
Bool next ();
Bool EOF ();
 
Void lock ();
Void unlock ();

PRIVATE:
Sqlhenv v_od_env _; // handle ODBC environment stores Environment Variables
Sqlhdbc v_od_hdbc _; // handle connection handle
Sqlhstmt v_od_hstmt _; // SQL statement handle
Sqlinteger v_od_rowanz _; // number of records affected by the operation
Sqlsmallint v_od_colanz _; // number of fields contained in records affected by the operation
Char * pszfield _ [field_num]; // stores a query result set, and the buffer zone is created based on the query results.
Int nmaxfiledlen _; // maximum value of the field
Bool bopened _;
Bool bconnected _;
Bool beof _;
 
Pthread_mutex_t mutex _;
Bool mutex_inited _;
};

# Endif

//. Cpp

/*************************************** *******
G ++ cppodbc. cpp-lodbc-g-o cppodbc

// Blog.csdn.net/bat603

// By Ben
**************************************** ******/
# Include "cppodbc. H"
# Include <string. h>

Cppodbc: cppodbc ()
{
Bopened _ = false;
Bconnected _ = false;
Nmaxfiledlen _= 512;
Beof _ = false;

For (INT I = 0; I <field_num; I ++)
Pszfield _ [I] = NULL;
 
Mutex_inited _ = false;
}

Cppodbc ::~ Cppodbc ()
{
If (mutex_inited _)
Pthread_mutex_destroy (& mutex _);
 
Clear ();
}
 
Bool cppodbc: open ()
{
If (bopened _) // already opened
Return true;

Long v_od_erg; // result of functions stores error code
 
// Allocate environment handle and register version
V_od_erg = sqlallochandle (SQL _handle_env, SQL _null_handle, & v_od_env _);
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Printf ("error allochandle/N ");
Return false;
}
 
V_od_erg = sqlsetenvattr (v_od_env _, SQL _attr_odbc_version, (void *) SQL _ov_odbc3, 0 );
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Printf ("error setenv/N ");
Sqlfreehandle (SQL _handle_env, v_od_env _);
Return false;
}
 
// Initialize the mutex
If (! Mutex_inited _)
{
Pthread_mutex_init (& mutex _, null );
Mutex_inited _ = true;
}
 
Bopened _ = true;
Return true;
}

Bool cppodbc: Close ()
{
If (bconnected _)
Return false;

Sqlfreehandle (SQL _handle_env, v_od_env _);
Bopened _ = false;
 
Return true;
}

Bool cppodbc: connect (const char * pszdsn, const char * pszuname, const char * pszupasswd)
{
If (! Bopened _)
Return false;

If (pszdsn = NULL)
Return false;

Long v_od_erg = 0;
Sqlchar v_od_stat [64] = {0}; // status of the SQL statement execution result
Sqlinteger v_od_err = 0; // error code after SQL statement execution
Sqlsmallint v_od_mlen = 0; // message text size returned by the error
Sqlchar v_od_msg [256] = {0}; // error message buffer
 
// Allocate connection handle, set timeout
V_od_erg = sqlallochandle (SQL _handle_dbc, v_od_env _, & v_od_hdbc _);
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Printf ("error allochdb % d/N", v_od_erg );
Return false;
}
 
// (Sqlpointer *)
V_od_erg = sqlsetconnectattr (v_od_hdbc _, SQL _login_timeout, (sqlpointer) 5, 0 );
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Printf ("error sqlsetconnectattr % d/N", v_od_erg );
Sqlfreehandle (SQL _handle_dbc, v_od_hdbc _);
Return false;
}
 
// Connect to the datasource
// Mysqlodbc // mypostgres // mysqlitedb
V_od_erg = sqlconnect (v_od_hdbc _, (sqlchar *) pszdsn, SQL _cnt,
(Sqlchar *) pszuname, SQL _cnt,
(Sqlchar *) pszupasswd, SQL _cnt );
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Printf ("error sqlconnect % d/N", v_od_erg );
Sqlgetdiagrec (SQL _handle_dbc, v_od_hdbc _, 1,
V_od_stat, & v_od_err, v_od_msg, 256, & v_od_mlen );
Printf ("% s (% d)/n", v_od_msg, v_od_err );
Sqlfreehandle (SQL _handle_dbc, v_od_hdbc _);
Return false;
}
 
Printf ("connected! /N ");
 
V_od_erg = sqlallochandle (SQL _handle_stmt, v_od_hdbc _, & v_od_hstmt _);
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Printf ("fehler im allocstatement % d/N", v_od_erg );
Sqlgetdiagrec (SQL _handle_dbc, v_od_hdbc _, 1, v_od_stat, & v_od_err, v_od_msg, 256, & v_od_mlen );
Printf ("% s (% d)/n", v_od_msg, v_od_err );
Sqldisconnect (v_od_hdbc _);
Sqlfreehandle (SQL _handle_dbc, v_od_hdbc _);
Return false;
}
 
Bconnected _ = true;
Return true;
}

Bool cppodbc: disconnect ()
{
If (bconnected _)
{
Sqlfreehandle (SQL _handle_stmt, v_od_hstmt _);
Sqldisconnect (v_od_hdbc _);
Sqlfreehandle (SQL _handle_dbc, v_od_hdbc _);
Bconnected _ = false;
}
 
Return true;
}

Unsigned int cppodbc: sqlquery (const char * pszsql)
{
If (pszsql = NULL)
Return 0;

Long v_od_erg = 0;
Sqlchar v_od_stat [64] = {0}; // status of the SQL statement execution result
Sqlinteger v_od_err = 0; // error code after SQL statement execution
Sqlsmallint v_od_mlen = 0; // message text size returned by the error
Sqlchar v_od_msg [256] = {0}; // error message buffer
Char * pszbuf = NULL;

// Clear the buffer
Clear ();
// Query
 
V_od_erg = sqlexecdirect (v_od_hstmt _, (sqlchar *) pszsql, SQL _nt );
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Printf ("error in select % d/N", v_od_erg );
Sqlgetdiagrec (SQL _handle_dbc, v_od_hdbc _, 1, v_od_stat, & v_od_err, v_od_msg, 256, & v_od_mlen );
Printf ("% s (% d)/n", v_od_msg, v_od_err );
Return 0;
}

// Obtain the number of query results
V_od_erg = sqlrowcount (v_od_hstmt _, & v_od_rowanz _);
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Return 0;
}

If (v_od_rowanz _ = 0) // No query results
Return 0;

// Obtain the number of result Fields
V_od_erg = sqlnumresultcols (v_od_hstmt _, & v_od_colanz _);
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Return 0;
}
Printf ("Number of columns % d/N", v_od_colanz _);

// Bind the Field Buffer
For (INT I = 0; I <v_od_colanz _; I ++)
{
Pszbuf = new char [nmaxfiledlen _ + 1];
Memset (pszbuf, 0, nmaxfiledlen _);
Pszfield _ [I] = pszbuf;
Sqlbindcol (v_od_hstmt _, I + 1, SQL _c_char, pszbuf, nmaxfiledlen _, & v_od_err );
}

// Get a row of results, and put the results in the bound buffer.
V_od_erg = sqlfetch (v_od_hstmt _);
If (v_od_erg! = SQL _no_data)
Beof _ = false;

Return v_od_rowanz _;
}

Bool cppodbc: clear ()
{
V_od_rowanz _ = 0;
V_od_colanz _ = 0;
Beof _ = true;
For (INT I = 0; I <field_num; I ++)
{
If (pszfield _ [I]! = NULL)
Delete [] pszfield _ [I];
Pszfield _ [I] = NULL;
}
Return true;
}

Unsigned int cppodbc: sqlexec (const char * pszsql)
{
If (pszsql = NULL)
Return 0;

Long v_od_erg = 0;
Sqlchar v_od_stat [64] = {0}; // status of the SQL statement execution result
Sqlinteger v_od_err = 0; // error code after SQL statement execution
Sqlsmallint v_od_mlen = 0; // message text size returned by the error
Sqlchar v_od_msg [256] = {0}; // error message buffer
Char * pszbuf = NULL;

// Clear the buffer
Clear ();
 
V_od_erg = sqlexecdirect (v_od_hstmt _, (sqlchar *) pszsql, SQL _nt );
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Printf ("error in select % d/N", v_od_erg );
Sqlgetdiagrec (SQL _handle_dbc, v_od_hdbc _, 1, v_od_stat, & v_od_err, v_od_msg, 256, & v_od_mlen );
Printf ("% s (% d)/n", v_od_msg, v_od_err );
Return 0;
}

// Obtain the number of query results
V_od_erg = sqlrowcount (v_od_hstmt _, & v_od_rowanz _);
If (v_od_erg! = SQL _success) & (v_od_erg! = SQL _success_with_info ))
{
Return 0;
}

Return v_od_rowanz _;
}

Unsigned int cppodbc: sqlexecautoid (char * pszsql)
{

If (pszsql = NULL | pszidfield = NULL)
Return 0;

// Different database processing methods
// The general method is stupid. You need to add the Automatically increasing field name as the parameter.
Unsigned long ulidentiy = 0;

Ulidentiy = sqlexec (pszsql );
If (ulidentiy = 0)
Return 0;

// Obtain the inserted data table
String STR = pszsql;

Transform (Str. Begin (), str. End (), str. Begin (), toupper );
Int nlen1 = Str. Find ("");
Int nlen2 = Str. Find ("values ");

STR = pszsql;
Nlen1 + = strlen ("");
String str1 = Str. substr (nlen1, nLen2-nLen1 );
Nlen1 = 0;
Nlen1 = str1.find ("(", 0); // search for left brackets from the beginning
If (nlen1> 0)
Str1 = str1.substr (0, nlen1); // remove the section with parentheses

STR = "select max (";
STR + = pszidfield;
STR + = ") from ";
STR + = str1;

Ulidentiy = sqlquery (Str. c_str ());
Ulidentiy = getintvalue (0 );

Return ulidentiy;

}

Bool cppodbc: isopen ()
{
Return bopened _;
}

// Number of query results. The number of updated records is returned during the update and the number of deleted records are returned during the deletion.
Unsigned int cppodbc: getcount ()
{
Return v_od_rowanz _;
}

// Two columns are returned for the query result.
Unsigned int cppodbc: getcolumns ()
{
Return v_od_colanz _;
}

Int cppodbc: getintvalue (unsigned int uiindex)
{
If (uiindex <0 | uiindex> v_od_colanz _)
Return 0;

Int nfield = 0;
If (pszfield _ [uiindex]! = NULL)
Nfield = atoi (pszfield _ [uiindex]);
Nfield = atoi (pszfield _ [uiindex]);
 
Return nfield;
}

Char * cppodbc: getstrvalue (unsigned int uiindex)
{
If (uiindex <0 | uiindex> v_od_colanz _)
Return NULL;
 
Return pszfield _ [uiindex];
}

// Cancel the operation
Bool cppodbc: Cancel ()
{

}

// Get error code
Unsigned int cppodbc: geterror ()
{

}

// Next
Bool cppodbc: Next ()
{
Long v_od_erg = 0;
 
V_od_erg = sqlfetch (v_od_hstmt _);
If (v_od_erg! = SQL _no_data)
Beof _ = false;
Else
Beof _ = true;

Return! Beof _;
}

Bool cppodbc: EOF ()
{
Return beof _;
}

Void cppodbc: Lock ()
{
If (! Mutex_inited _)
Return;

Pthread_mutex_lock (& mutex _);
}

Void cppodbc: Unlock ()
{
If (! Mutex_inited _)
Return;

Pthread_mutex_unlock (& mutex _);
}

Int main ()
{
Cppodbc;
 
Bool Bres = cppodbc. open ();
If (! Bres)
{
Printf ("Open error! /N ");
Return 0;
}
Printf ("Open OK! /N ");
Bres = cppodbc. Connect ("mysqlodbc", "lizp", "lizp ");
If (! Bres)
{
Printf ("Connect error! /N ");
Return 0;
}

Printf ("Connect OK! /N ");
Int nres = 0;

// Insert into userinfo values ('44', 'osbctest22 ')
Nres = cppodbc. sqlexec ("Update userinfo set UID = '55' where uid = '44 '");

Printf ("sqlexec the nres is % d/N", nres );

Nres = cppodbc. sqlquery ("select uid, uname from userinfo ");
Printf ("sqlquery the nres is % d/N", nres );
 
Char * pszbuf = NULL;
Int nbuf = 0;
Int I = 0;
While (! Cppodbc. EOF ())
{
I = 0;
Nbuf = cppodbc. getintvalue (I ++ );
Printf ("uid is % d/N", nbuf );

// Nbuf = cppodbc. getintvalue (I ++ );
// Printf ("uid is % d/N", nbuf );

Pszbuf = cppodbc. getstrvalue (I ++ );
Printf ("uname is % s/n", pszbuf );

Cppodbc. Next ();

// Getchar ();
}
 
Cppodbc. Disconnect ();
Cppodbc. Close ();
 
Return 0;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.