RSS
 

SQLite wrapper

19 Sep

If you need a database to support your anti spam filter consider SQLite for an embedded database.

Use the following class to execute a query:


//
// SQLiteQuery helper
//
// use like this
// SQLiteQuery sqlQuery( lpszPath, szQuery );
// for( ; SUCCEEDED( sqlQuery.GetStatus() ); sqlQuery.GetNext() )
// {
// CString strValue = sqlQuery.GetCurrentAsText( 0 );
// }
//
class SQLiteQuery
{
public:
//
// constructor
//
SQLiteQuery( const TCHAR * lpszPath, const TCHAR * szQuery )
{
    m_pDatabase = NULL;
    m_pStatementQuery = NULL;
    m_result = SQLITE_OK;
 
    Start( lpszPath, szQuery );
}
 
 
//
// destructor
//
~SQLiteQuery()
{
    Stop();
}
 
//
// get status
//
HRESULT GetStatus()
{
    if ( m_pDatabase && m_pStatementQuery && m_result == SQLITE_ROW )
        return S_OK;
    return E_FAIL;
}
 
//
// get status exec
//
HRESULT GetStatusExec()
{
    if ( m_pDatabase && m_pStatementQuery && m_result == SQLITE_DONE )
        return S_OK;
    return E_FAIL;
}
 
//
// go next
//
void GetNext()
{
    if ( m_pDatabase && m_pStatementQuery )
    {
        m_result = sqlite3_step ( m_pStatementQuery );
        if ( m_result != SQLITE_ROW )
            Stop();
    }
}
 
//
// get column text or column int
//
CString GetCurrentAsText( int column = 0 )
{
    if ( m_pDatabase == NULL || m_pStatementQuery == NULL )
        return CString( _T("") );
 
    TCHAR * szValue = (TCHAR *) sqlite3_column_text16( m_pStatementQuery, column );
    return CString( szValue );
}
 
int GetCurrentAsInt( int column = 0 )
{
    if ( m_pDatabase == NULL || m_pStatementQuery == NULL )
        return 0;
 
    return (int) sqlite3_column_int( m_pStatementQuery, column );
}
 
 
protected:
//
// start
//
void Start( const TCHAR * lpszPath, const TCHAR * szQuery )
{
    //
    // open
    //
    m_result = sqlite3_open16( lpszPath, &m_pDatabase );
    if ( m_result != SQLITE_OK || m_pDatabase == NULL )
    {
        m_pDatabase = NULL;
        Stop();
        return;
    }
 
    //
    // prepare
    //
    m_result = sqlite3_prepare16_v2( m_pDatabase, szQuery, -1, &m_pStatementQuery, NULL );
    if ( m_result != SQLITE_OK || m_pStatementQuery == NULL )
    {
        m_pStatementQuery = NULL;
        Stop();
        return;
    }
 
    //
    // SQLITE_DONE || SQLITE_ROW
    //
    m_result = sqlite3_step ( m_pStatementQuery );
    if ( m_result != SQLITE_ROW && m_result != SQLITE_DONE )
    {
        Stop();
    }
}
 
//
// stop
//
void Stop()
{
    if ( m_pStatementQuery )
        m_result = sqlite3_finalize( m_pStatementQuery );
    if ( m_pDatabase )
        m_result = sqlite3_close( m_pDatabase );
 
    m_pStatementQuery = NULL;
    m_pDatabase = NULL;
    m_result = SQLITE_ERROR;
 
}
 
protected:
    sqlite3 * m_pDatabase;
    sqlite3_stmt * m_pStatementQuery;
    int m_result;
 
};

 
Comments Off

Posted in All, Devel, Spamfilter

 

Tags:

Comments are closed.