Encapsulation of the UNIXODBC

Source: Internet
Author: User

This code can be reproduced arbitrarily use, but please keep the source

blog.csdn.net/bat603

by Ben

//

. h

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

url:blog.csdn.net/bat603
Description: Using the tutorial in the UNIXODBC home page, the UNIXODBC is encapsulated and the lock function is added, 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 fields for a query
#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 results of the query, returns the number of updated records when updated, and returns the number of deletes when deleted
unsigned int getcount ();
Returns the number of columns in the query results two
unsigned int getcolumns ();
int getintvalue (unsigned int uiindex);
char * getstrvalue (unsigned int uiindex);
Cancel 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 Storage environment variables
SQLHDBC v_od_hdbc_; Handle Connection Connection Handle
Sqlhstmt V_od_hstmt_; Handle to SQL statement
Sqlinteger v_od_rowanz_; Number of records affected by operation
Sqlsmallint V_od_colanz_; The number of fields the record that the action affects contains
char* Pszfield_[field_num]; Holds a query result set that the buffer creates based on query results
int nmaxfiledlen_; The maximum value of a 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 (&AMP;MUTEX_);

Clear ();
}

BOOL Cppodbc::open ()
{
if (bopened_)//has been opened
return true;

Long V_od_erg; Result of functions holds the error code

Allocate environment handle and register version
V_od_erg = Sqlallochandle (sql_handle_env, Sql_null_handle, &AMP;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;
}

Initializing a 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 SQL execution result state of SQL statement
Sqlinteger v_od_err = 0; Error code after execution of SQL statement
Sqlsmallint V_od_mlen = 0; Message text size returned by 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_nts,
(sqlchar*) Pszuname, Sql_nts,
(sqlchar*) pszupasswd, sql_nts);
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::D isconnect ()
{
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 SQL execution result state of SQL statement
Sqlinteger v_od_err = 0; Error code after execution of SQL statement
Sqlsmallint V_od_mlen = 0; Message text size returned by error
SQLCHAR v_od_msg[256] = {0};//error message buffer
char* pszbuf = NULL;

Empty buffer
Clear ();
Inquire

V_od_erg=sqlexecdirect (V_od_hstmt_, (sqlchar*) pszsql, sql_nts);
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;
}

Get 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;

Get 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_);

Bound field buffers
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 it in a 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 SQL execution result state of SQL statement
Sqlinteger v_od_err = 0; Error code after execution of SQL statement
Sqlsmallint V_od_mlen = 0; Message text size returned by error
SQLCHAR v_od_msg[256] = {0};//error message buffer
char* pszbuf = NULL;

Empty buffer
Clear ();

V_od_erg=sqlexecdirect (V_od_hstmt_, (sqlchar*) pszsql, sql_nts);
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;
}

Get 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 are different
The general approach is relatively stupid, need to increase the automatic growth field name as a parameter
unsigned long ulidentiy = 0;

ulidentiy = SqlExec (Pszsql);
if (ulidentiy = 0)
return 0;

Gets the data table for the insert operation
string str = Pszsql;

Transform (Str.begin (), Str.end (), Str.begin (), toupper);
int nLen1 = Str.find ("into");
int nLen2 = Str.find ("VALUES");

str = pszsql;
NLen1 + = strlen ("into");
String str1 = Str.substr (NLen1, NLEN2-NLEN1);
NLEN1 = 0;
NLen1 = Str1.find ("(", 0);//Find opening parenthesis from start
if (NLen1 > 0)
str1 = str1.substr (0, NLEN1);//elimination of parenthesized parts

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 results of the query, returns the number of updated records when updated, and returns the number of deletes when deleted
unsigned int cppodbc::getcount ()
{
return v_od_rowanz_;
}

Returns the number of columns in the query results two
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 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 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 (' ', ' ODBCTest22 ')
Nres = Cppodbc.sqlexec ("UPDATE UserInfo SET uid= ' 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.