/*
g_DBMySql.cpp: implementation of the CG_DBMySql class.
*/
#include "g_dbmysql.h"
CG_DBMySql::CG_DBMySql()
{
m_handle = NULL;
m_res = NULL;
SetLog(true);
}
CG_DBMySql::~CG_DBMySql()
{
Close();
}
bool CG_DBMySql::Connect(const char *host, int port,const char *name,const char *pwd,const char *db)
{
Close();
m_handle = mysql_init(NULL);
if (m_handle==NULL) return false;
if (port == 0) port = MYSQL_PORT;
if (mysql_real_connect(m_handle, host, name, pwd, NULL, port, NULL, 0) == NULL)
{
ShowError();
return false;
}
if (mysql_select_db(m_handle, db) != 0)
{
ShowError();
return false;
}
return true;
}
void CG_DBMySql::Close()
{
if (m_handle)
{
mysql_close(m_handle);
m_handle = NULL;
}
if (m_res)
{
mysql_free_result(m_res);
m_res = NULL;
}
}
bool CG_DBMySql::Query(const char *sql,int len)
{
if (!m_handle) return false;
if (len == 0) len = strlen(sql);
if (mysql_real_query(m_handle, sql, len) != 0)
{
ShowError();
return false;
}
if (m_res != NULL) mysql_free_result(m_res);
m_res = mysql_store_result(m_handle);
if (m_res != NULL)
{
m_fieldCnt = mysql_num_fields(m_res);
m_fields = mysql_fetch_fields(m_res);
}
return true;
}
int CG_DBMySql::GetFieldCount()
{
return m_fieldCnt;
}
int CG_DBMySql::GetRowCount()
{
return (int)mysql_num_rows(m_res);
}
void CG_DBMySql::ShowError()
{
if(m_log)
Sys_Log("SQL EER = [%s]", mysql_error(m_handle));
}
bool CG_DBMySql::GetRow()
{
m_row = mysql_fetch_row(m_res);
if (m_row == NULL) return false;
return true;
}
char *CG_DBMySql::GetField(char *fname, int *pnLen)
{
int i;
unsigned long *lengths;
lengths = mysql_fetch_lengths(m_res);
for(i = 0; i < m_fieldCnt; i++)
{
if (strcmp(fname,m_fields[i].name)==0)
{
if(pnLen) *pnLen = lengths[i];
return m_row[i];
}
}
return NULL;
}
//-------------------------------------
// Get Field Name , Data Type And Value
//-------------------------------------
bool CG_DBMySql::GetField(int idx,char *field,int *type,char **value)
{
if(idx<0 || idx>m_fieldCnt)
return false;
strcpy(field,m_fields[idx].name);
*type = m_fields[idx].type;
*value = m_row[idx];
return true;
}
//------------------------
// Get Field Name And Type
//------------------------
int CG_DBMySql::GetFieldInfo(int nIdx, char *pszName)
{
if(nIdx<0 || nIdx>=m_fieldCnt)
{
return 0;
}
if(pszName)
{
strcpy(pszName, m_fields[nIdx].name);
}
return m_fields[nIdx].type;
}
//------------------------------
// Get Field Data Type And Value
//------------------------------
bool CG_DBMySql::GetFieldContent(int nIdx , int *pnType , char **ppValue)
{
if(nIdx<0 || nIdx>=m_fieldCnt)
{
return false;
}
*pnType = m_fields[nIdx].type;
*ppValue = m_row[nIdx];
return true;
}
unsigned long CG_DBMySql::GetInsertId()
{
return (unsigned long)mysql_insert_id(m_handle);
}
long CG_DBMySql::GetAffectedRows()
{
return (unsigned long)mysql_affected_rows(m_handle);
}
void CG_DBMySql::SetLog(bool log)
{
m_log = log;
}