⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbengine.cpp

📁 在symbian2.0平台上开发的图书管理系统
💻 CPP
字号:
/*
 * ============================================================================
 *  Name     : BookstoreDb from DBEngine.cpp
 *  Part of  : BookstoreDb
 *  Created  : 8.12.2003 by Forum Nokia
 *  Version  : 1.0
 *  Copyright: Nokia Corporation
 * ============================================================================
 */

#include <badesca.h>    // CDesCArrayFlat
#include <s32file.h>    // CFileStore & CPermanentFileStore
#include <bautils.h>    // file helpers
#include <eikenv.h>
#include "DBEngine.h"

// Implementation specific constants
const int KCustomSqlMaxLength = 256;
const int KArrayGranularity = 5;     // for CDesCArrayFlat

// ---------------------------------------------------------------------------
// CBookstoreDb::NewL()
//
// Create instance of the bookstore database engine.
// ---------------------------------------------------------------------------
CBookstoreDb* CBookstoreDb::NewL()
    {
    CBookstoreDb* tmp = new (ELeave)CBookstoreDb();
    CleanupStack::PushL(tmp);
    tmp->ConstructL();
    CleanupStack::Pop();
    return tmp;
    }

// ---------------------------------------------------------------------------
// CBookstoreDb::~CBookstoreDb()
//
// Destructor of the bookstore database engine. Release resources.
// ---------------------------------------------------------------------------
CBookstoreDb::~CBookstoreDb()
    {
    Close();  // Just in case, if the user does not close this explicitely
    iFsSession.Close();
    }

// ---------------------------------------------------------------------------
// CBookstoreDb::ConstructL()
//
// Second phase construction. Leaves, if RFs session cannot be created.
// ---------------------------------------------------------------------------
void CBookstoreDb::ConstructL()
    {
    TInt err = iFsSession.Connect();
    if(err)
        User::Leave(err);
    }

// ---------------------------------------------------------------------------
// CBookstoreDb::CBookstoreDb()
//
// Constructor
// ---------------------------------------------------------------------------
CBookstoreDb::CBookstoreDb()
    {
    iOpen = EFalse;
    }

// ---------------------------------------------------------------------------
// CBookstoreDb::OpenDbL()
//
// Open existing bookstore database for exclusive access.
// ---------------------------------------------------------------------------
TInt CBookstoreDb::OpenDbL(const TFileName& aExistingBookstoreFile)
    {
    Close();

    if(!BaflUtils::FileExists(iFsSession, aExistingBookstoreFile))
        {
            return KErrNotFound;
        }

    iFileStore = CPermanentFileStore::OpenL(iFsSession,
        aExistingBookstoreFile, EFileRead|EFileWrite);
    iFileStore->SetTypeL(iFileStore->Layout());       // Set file store type
    iBookstoreDb.OpenL(iFileStore,iFileStore->Root());
    iOpen = ETrue;
    return KErrNone;
    }


// ---------------------------------------------------------------------------
// CBookstoreDb::Close()
//
// Close the database.
// ---------------------------------------------------------------------------
TInt CBookstoreDb::Close()
    {
    iBookstoreDb.Close();
    if(iFileStore)
        {
        delete iFileStore;
        iFileStore = NULL;
        }
    iOpen = EFalse;
    return KErrNone;
    }

// ---------------------------------------------------------------------------
// CBookstoreDb::IsOpen()
//
// Return open status of the database.
// ---------------------------------------------------------------------------
TBool CBookstoreDb::IsOpen() const
    {
    return iOpen;
    }

CDesCArrayFlat* CBookstoreDb::GetAllBooksL()
{
    TPtrC author, title;
    TBuf<KDescriptionMaxLength> description;
    TBuf<KBookItemMaxLength> rowText;
	
    RDbTable table;
    TInt err = table.Open(iBookstoreDb, KBooksTable, table.EReadOnly);
    User::LeaveIfError(err);
	
    CDesCArrayFlat* resultArray =
        new (ELeave)CDesC16ArrayFlat(KArrayGranularity);
    CleanupStack::PushL(resultArray);
	
    table.Reset();
    CDbColSet* colSet = table.ColSetL();
    CleanupStack::PushL(colSet);
	
    for (table.FirstL(); table.AtRow(); table.NextL())
	{
        description.Zero();
        rowText.Zero();
		
        table.GetL();
		
        author.Set(table.ColDes(colSet->ColNo(KBooksAuthorCol)));
        title.Set(table.ColDes(colSet->ColNo(KBooksTitleCol)));
		
        TDbColNo descrColNo = colSet->ColNo(KBooksDescriptionCol);
        RDbColReadStream readStream;       // A stream object for long columns
        readStream.OpenLC(table,descrColNo);
        readStream.ReadL(description, table.ColLength(descrColNo));
        readStream.Close();
        CleanupStack::Pop(); //readStream
		
        rowText.Append(author);
        rowText.Append(KSeparator);
        rowText.Append(title);
        rowText.Append(KSeparator);
        rowText.Append(description);
		
        resultArray->AppendL(rowText); // Copy rowText to resultArray
	}
    CleanupStack::PopAndDestroy(colSet);
    CleanupStack::Pop(resultArray);
    table.Close();
	
    return resultArray;
}


// ---------------------------------------------------------------------------
// CBookstoreDb::GetABookFastL()
//
// Get a book using index. Format of the result is:
//      <Author>|<Title>|<Description>
// ---------------------------------------------------------------------------
TInt CBookstoreDb::GetABookFastL(const TDesC& aTitle, TDes& aResult)
    {
    TInt err = KErrNone;
    TBuf<KDescriptionMaxLength> description; // Only 128 first characters read
    RDbTable rowset;

    TDbSeekKey seekKey(aTitle); // Initialize one-column seek key

    // Open view to "Books" table. Use index to browse the table.
    User::LeaveIfError(
        rowset.Open(iBookstoreDb, KBooksTable, rowset.EReadOnly));
    User::LeaveIfError(
        rowset.SetIndex(KBooksIndexName));

    // Query colum numbers for author, title, and description
    CDbColSet* colSet = rowset.ColSetL();
    CleanupStack::PushL(colSet);
    TInt authorColumnNo = colSet->ColNo(KBooksAuthorCol);
    TInt titleColumnNo = colSet->ColNo(KBooksTitleCol);
    TInt descrColumnNo = colSet->ColNo(KBooksDescriptionCol);
    CleanupStack::PopAndDestroy(colSet);

    // Search the index for aTitle
    if( rowset.SeekL(seekKey) )
        {
        rowset.GetL();

        RDbColReadStream readStream;     // A stream object for long columns
        readStream.OpenLC(rowset,descrColumnNo);
        readStream.ReadL(description, rowset.ColLength(descrColumnNo));
        readStream.Close();
        CleanupStack::Pop(); //readStream

        aResult.Zero();
        aResult.Append(rowset.ColDes(authorColumnNo));
        aResult.Append(KSeparator);
        aResult.Append(rowset.ColDes(titleColumnNo));
        aResult.Append(KSeparator);
        aResult.Append(description);

        err = KErrNone;
        }
    else
        {
        err = KErrNotFound;
        }

    rowset.Close();
    return err;
    }

// ---------------------------------------------------------------------------
// CBookstoreDb::GetBooksByKeyL()
//
// Get array of books from database according to column name and a search
// pattern. Format of each array item is:
//      <Author>|<Title>|<Description>
// ---------------------------------------------------------------------------
CDesCArrayFlat* CBookstoreDb::GetBooksByKeyL(const TDesC& aColumnName,
    const TDesC& aSearchString)
    {

    TPtrC author, title;
    TBuf<KDescriptionMaxLength> description;
    TBuf<KBookItemMaxLength> rowText;

    // Sql: SELECT Author, Title, Description FROM Books
    //      WHERE "aColumnName LIKE aSearchString"
    //      ORDER BY Title, Author
    TBuf<KCustomSqlMaxLength> sqlStr;
    sqlStr.Append(_L("SELECT "));
    sqlStr.Append(KBooksAuthorCol);
    sqlStr.Append(_L(", "));
    sqlStr.Append(KBooksTitleCol);
    sqlStr.Append(_L(", "));
    sqlStr.Append(KBooksDescriptionCol);
    sqlStr.Append(_L(" FROM "));
    sqlStr.Append(KBooksTable);
    sqlStr.Append(_L(" WHERE "));
    sqlStr.Append(aColumnName);
    sqlStr.Append(_L(" LIKE '"));
    sqlStr.Append(aSearchString);
    sqlStr.Append(_L("' ORDER BY "));
    sqlStr.Append(KBooksTitleCol);
    sqlStr.Append(_L(", "));
    sqlStr.Append(KBooksAuthorCol);

    CDesCArrayFlat* resultArray =
        new (ELeave)CDesC16ArrayFlat(KArrayGranularity);
    CleanupStack::PushL(resultArray);

    // Create a view on the database
    RDbView view;
    User::LeaveIfError(
        view.Prepare(iBookstoreDb, TDbQuery(sqlStr), view.EReadOnly));
    User::LeaveIfError(view.EvaluateAll());

    CDbColSet* colSet = view.ColSetL();
    CleanupStack::PushL(colSet);

    // Append each result row to array
    for (view.FirstL(); view.AtRow(); view.NextL())
        {

        description.Zero();
        rowText.Zero();

        view.GetL();

        author.Set(view.ColDes(colSet->ColNo(KBooksAuthorCol)));
        title.Set(view.ColDes(colSet->ColNo(KBooksTitleCol)));

        TDbColNo descrColNo = colSet->ColNo(KBooksDescriptionCol);
        RDbColReadStream readStream;       // A stream object for long columns
        readStream.OpenLC(view, descrColNo);
        readStream.ReadL(description, view.ColLength(descrColNo));
        readStream.Close();
        CleanupStack::Pop(); //readStream

        rowText.Append(author);
        rowText.Append(KSeparator);
        rowText.Append(title);
        rowText.Append(KSeparator);
        rowText.Append(description);

        resultArray->AppendL(rowText);
        }
    CleanupStack::PopAndDestroy(colSet);
    view.Close();
    CleanupStack::Pop(resultArray);

    return resultArray;

    }


// ---------------------------------------------------------------------------
// CBookstoreDb::UpdateBookTitle()
//
// Update book title using SQL UPDATE.
// ---------------------------------------------------------------------------
//
TInt CBookstoreDb::UpdateBookTitle(const TDesC& aOldTitleKey,
    const TDesC& aNewTitle)
    {
    _LIT(KSQLUpdateStart, "UPDATE Books SET Title = '");
    _LIT(KSQLUpdateMiddle, "' WHERE Title = '");
    _LIT(KSQLUpdateEnd, "'");

    TBuf<KCustomSqlMaxLength> sqlStr;
    sqlStr.Append(KSQLUpdateStart);
    sqlStr.Append(aNewTitle);
    sqlStr.Append(KSQLUpdateMiddle);
    sqlStr.Append(aOldTitleKey);
    sqlStr.Append(KSQLUpdateEnd);

    return iBookstoreDb.Execute(sqlStr);
    }



// ---------------------------------------------------------------------------
// CBookstoreDb::HasDateColumn()
//
// Tests wheter the Books table has date column
// ---------------------------------------------------------------------------
TInt CBookstoreDb::HasDateColumn(TBool& aReturnValue)
    {
    RDbTable booksTable;
    aReturnValue = EFalse;

    // Open the Books table.
    User::LeaveIfError(
        booksTable.Open(iBookstoreDb, KBooksTable, booksTable.EReadOnly));
    CleanupClosePushL(booksTable);  // Remember to pop and close

    // Iterate through the colums of Books table. Check whether there is
    // a 'PublishDate' column
    CDbColSet* colSet = booksTable.ColSetL();
    CleanupStack::PushL(colSet);
    TDbColSetIter colIter(*colSet);
    while(colIter)
        {
        if( (colIter->iName).Compare(KBooksDateCol) == 0) // 0 = equal
            {
            aReturnValue = ETrue;
            break;
            }
        colIter++;
        }
    CleanupStack::PopAndDestroy(colSet);

    // Pop the booksTable from cleanup stack and close it.
    CleanupStack::PopAndDestroy();

    return KErrNone;
    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -