コード例 #1
0
void CIndustryDetailDialog_Commodities::Save()
{
    CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB;
    //
    for( int i=0;i<m_ctlCommodityListIn.GetItemCount();i++ )
    {
        if( m_ctlCommodityListIn.GetCheck(i) )
        {
            int iCommodityFK = m_ctlCommodityListIn.GetItemData(i);
            int iLoadEmpty = atoi(m_ctlCommodityListIn.GetItemText(i,1));
            int iQuanHigh = atoi(m_ctlCommodityListIn.GetItemText(i,2));
            int iQuanLow = atoi(m_ctlCommodityListIn.GetItemText(i,3));
            int iPercent = atoi(m_ctlCommodityListIn.GetItemText(i,4));
            CString sSQL;
            sSQL.Format("INSERT INTO Industries_Commodities (Industries_FK,Commodities_FK,InOut,LoadEmptyDays,Quantity_low,Quantity_high,Quantity_percentage) VALUES (%d,%d,0,%d,%d,%d,%d);",m_iIndustryID,iCommodityFK,iLoadEmpty,iQuanLow,iQuanHigh,iPercent);
            CppSQLite3Query q = pDB->execQuery(sSQL);
            q.finalize();
        }
    }
    for( i=0;i<m_ctlCommodityListOut.GetItemCount();i++ )
    {
        if( m_ctlCommodityListOut.GetCheck(i) )
        {
            int iCommodityFK = m_ctlCommodityListOut.GetItemData(i);
            int iLoadEmpty = atoi(m_ctlCommodityListOut.GetItemText(i,1));
            int iQuanHigh = atoi(m_ctlCommodityListOut.GetItemText(i,2));
            int iQuanLow = atoi(m_ctlCommodityListOut.GetItemText(i,3));
            int iPercent = atoi(m_ctlCommodityListOut.GetItemText(i,4));
            CString sSQL;
            sSQL.Format("INSERT INTO Industries_Commodities (Industries_FK,Commodities_FK,InOut,LoadEmptyDays,Quantity_low,Quantity_high,Quantity_percentage) VALUES (%d,%d,1,%d,%d,%d,%d);",m_iIndustryID,iCommodityFK,iLoadEmpty,iQuanLow,iQuanHigh,iPercent);
            CppSQLite3Query q = pDB->execQuery(sSQL);
            q.finalize();
        }
    }
}
コード例 #2
0
//private
void RPGMapItemsMenuLayer::loadItemsData()
{
    //道具数据
    this->m_itemsList->removeAllObjects();
    
    CppSQLite3Query query = this->m_db->execQuery(ITEMS_EXISTING_QUERY);
    while(!query.eof())
    {
        RPGExistingItems *itemsData = RPGExistingItems::create();
        itemsData->m_dataId = query.getIntField("id");
        itemsData->m_name = query.getStringField("name_cns");
        itemsData->m_buy = query.getIntField("buy");
        itemsData->m_sell = query.getIntField("sell");
        itemsData->m_type = query.getIntField("type");
        itemsData->m_attack = query.getFloatField("attack");
        itemsData->m_defense = query.getFloatField("defense");
        itemsData->m_speed = query.getFloatField("speed");
        itemsData->m_skillAttack = query.getFloatField("skill_attack");
        itemsData->m_skillDefense = query.getFloatField("skill_defense");
        itemsData->m_total = query.getIntField("total");
        this->m_itemsList->addObject(itemsData);
        
        query.nextRow();
    }
    query.finalize();
    
    CCTableView *tableView = (CCTableView*)this->getChildByTag(kRPGMapItemsMenuLayerTagItemListTable);
    tableView->reloadData();
}
コード例 #3
0
BOOL CLocationDetailDialog::OnInitDialog()
{
    CDialog::OnInitDialog();

    if( m_iLocationID == -1 )
        m_ctlOK.EnableWindow(FALSE);
    else
    {
        CString sSQL;
        sSQL.Format("SELECT name,notes FROM Locations WHERE id=%d;",m_iLocationID);
        CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB;
        CppSQLite3Query q = pDB->execQuery(sSQL);
        //
        if (!q.eof())
        {
            m_sLocationName = q.getStringField("name");
            m_sLocalInstructions = q.getStringField("notes");
        }
        q.finalize();
        UpdateData(FALSE);
    }

    return TRUE;  // return TRUE unless you set the focus to a control
    // EXCEPTION: OCX Property Pages should return FALSE
}
コード例 #4
0
BOOL CCarTypesDetailDialog::OnInitDialog() 
{
	CDialog::OnInitDialog();
	
	// TODO: Add extra initialization here

    if( m_iCarTypeFK != -1 )
    {
        CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB;
        CString sSQL;
        sSQL.Format("SELECT * FROM CarTypes WHERE id=%d",m_iCarTypeFK);
        CppSQLite3Query q = pDB->execQuery((LPCTSTR)sSQL);
        if( !q.eof() )
        {
            m_sCarTypeDescription = q.getStringField("description");
            m_sCarTypeID = q.getStringField("type_id");
            m_bPassenger = q.getIntField("passenger")==1?TRUE:FALSE;
        }
        q.finalize();
    }


    UpdateData(FALSE);
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}
コード例 #5
0
ファイル: BrainMemory.cpp プロジェクト: GMIS/GMIS
void   CBrainMemory::SetSystemItem(int64 Item,AnsiString Info){
	CppSQLite3Buffer SQL;
	CppSQLite3Query  Result;
	char a[30],b[30];
     int64toa(ROOM_SYSTEM,a);
	 int64toa(Item,b);

    SQL.format("select b from \"%s\" where a = \"%s\";",a,b);				
	Result = BrainDB.execQuery(SQL);
	bool Find = !Result.eof();
    Result.finalize();

	if(!Find){
		SQL.format("insert into \"%s\" values (\"%s\", ?)",
			a,
			b);
	}else{
		SQL.format("update \"%s\" set b = ? where a = \"%s\";",
			a,
			b
			);
	}

	CppSQLite3Statement State = BrainDB.compileStatement(SQL);
	State.bind(1,Info.c_str()); //替换第一个问号
	State.execDML();

}
コード例 #6
0
void CTerminateNewLocationDialog::OnSelchangeLocationlist() 
{
    int iLocationID = m_ctlLocationList.GetItemData(m_ctlLocationList.GetCurSel());
    CString sSQL;
    sSQL.Format("SELECT Industries.id,Industries.name FROM Industries,Sidings WHERE Industries.Sidings_FK=Sidings.id AND Sidings.Locations_FK=%d",iLocationID);
    TRACE(sSQL);
    //
    CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB;
    CppSQLite3Query q = pDB->execQuery(sSQL);
    //
    while( m_ctlIndustryList.GetCount() > 0 )
        m_ctlIndustryList.DeleteString(0);
    //
    while (!q.eof())
    {
        int nIndex = m_ctlIndustryList.AddString(q.getStringField("name"));
        m_ctlIndustryList.SetItemData(nIndex,q.getIntField("id"));
        q.nextRow();
    }
    //
    sSQL.Format("SELECT id,name FROM Sidings WHERE Locations_FK=%d;",iLocationID);
    q = pDB->execQuery(sSQL);
    //
    while( m_ctlSidingList.GetCount() > 0 )
        m_ctlSidingList.DeleteString(0);
    //
    while (!q.eof())
    {
        int nIndex = m_ctlSidingList.AddString(q.getStringField("name"));
        m_ctlSidingList.SetItemData(nIndex,q.getIntField("id"));
        q.nextRow();
    }
    q.finalize();
}
コード例 #7
0
CString CEquipmentLocationDialog::GetCarType(int iCarTypeFK)
{
    CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB;
    CString sSQL;
    sSQL.Format("SELECT description FROM CarTypes WHERE id=%d;",iCarTypeFK);
    CppSQLite3Query q = pDB->execQuery(sSQL);
    CString sType("");
    if( !q.eof() )
        sType = q.getStringField("description");
    q.finalize();
    return sType;
}
コード例 #8
0
bool RPGMapSceneLayer::init(float showObjectTime)
{
    if(RPGBaseSceneLayer::init())
    {        
        CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("joystick.plist");
        CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("main.plist");
        
        //加载语言文件
        string languageFile = CCFileUtils::sharedFileUtils()->fullPathForFilename("scene_map_cns.plist");
        this->m_stringList = CCDictionary::createWithContentsOfFileThreadSafe(languageFile.c_str());
        this->m_stringList->retain();
        
        //数据库部分,读取进度记录
        CppSQLite3Query query = this->m_db.execQuery(SAVEDATA_MAP_QUERY);
        this->m_mapData.mapId = query.getIntField("map_id");
        this->m_mapData.mapName = query.getStringField("map_name");
        this->m_mapData.hasEnemy = query.getIntField("has_enemy") == 1 ? true : false;
        this->m_mapData.bgAudio = query.getStringField("bg_audio");
        this->m_mapData.playerToX = query.getFloatField("player_to_x");
        this->m_mapData.playerToY = query.getFloatField("player_to_y");
        this->m_mapData.playerDirection = query.getStringField("player_direction");
        this->m_mapData.location = query.getStringField("location_cns");
        this->m_mapData.gold = query.getIntField("gold");
        query.finalize();
        
        CCTMXTiledMap *bgMap = CCTMXTiledMap::create(this->m_mapData.mapName.c_str());
        bgMap->setTag(kRPGMapSceneLayerTagBgMap);
        bgMap->setPosition(ccp((CCDirector::sharedDirector()->getWinSize().width - bgMap->getContentSize().width) / 2.0, (CCDirector::sharedDirector()->getWinSize().height - bgMap->getContentSize().height) / 2.0));
        this->addChild(bgMap);
        
        //背景音乐
        if(SimpleAudioEngine::sharedEngine()->isBackgroundMusicPlaying())
        {
            SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(true);
            SimpleAudioEngine::sharedEngine()->playBackgroundMusic(this->m_mapData.bgAudio.c_str(), true);
        }
        
        this->m_playerMoveAct = NULL;
        this->m_playerMoveSpeed = GAME_PLAYER_MOVESPEED;
        this->m_touchedDialogNPC = NULL;
        this->m_dialogDirection = kRPGMapSceneLayerDialogDirectionNone;
        
        this->m_hasEnemy = this->m_mapData.hasEnemy; //是否会遇敌
        this->m_releaseTexture = false; //是否在释构方法里面释放占用纹理
        
        this->scheduleOnce(schedule_selector(RPGMapSceneLayer::startPlay), showObjectTime);
        
//        CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo();
        return true;
    }
    return false;
}
コード例 #9
0
CppSQLite3Query* StoreDatabase::execute(CppSQLite3DB* db, CCString* sql)
{
    CppSQLite3Query* query = new CppSQLite3Query();
    try {
        *query = db->execQuery(sql->getCString());
    } catch (CppSQLite3Exception &e) {
        CCLOG("%d : %s", e.errorCode(), e.errorMessage());
        query->finalize();
        CC_SAFE_DELETE(query);
        query = NULL;
    }
    return query;
}
コード例 #10
0
ファイル: RCGen.cpp プロジェクト: MFDonadeli/PMA
void CRcGen::_FormatList(int nIdList)
{
	int iSize=0;
	CStringA sQuery;	
	CppSQLite3Query q;
	m_listctrl->SetExtendedStyle(LVS_EX_FULLROWSELECT);	

	try
	{
		sQuery.Format("select count(*) from reslists where IDList = %d", nIdList);

		q = m_pDB->execQuery(sQuery); 
		
		if(!q.eof())
		{
			q.finalize();

			sQuery.Format("select * from reslists where idlist = %d", nIdList);
			q = m_pDB->execQuery(sQuery);

			CRect r;
			m_listctrl->GetWindowRect(r);		

			//iSize = (r.right - r.left) / q.getIntField(0);
			iSize = q.getIntField("Largura");

			for(int i=0;!q.eof();i++)
			{
				//m_listctrl->InsertColumn(i, CString(q.getStringField("NomeColuna")), LVCFMT_LEFT, DRA::SCALEX(iSize));
				m_listctrl->InsertColumn(i, CString(q.getStringField("NomeColuna")), LVCFMT_LEFT, iSize);
				q.nextRow();
			}
			q.finalize();						
		}		
	}
	catch(CppSQLite3Exception e)
	{
	}
}
コード例 #11
0
ファイル: AppDelegate.cpp プロジェクト: ChinaiOS/OzgGameRPG
bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    CCDirector* pDirector = CCDirector::sharedDirector();
    CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();

    pDirector->setOpenGLView(pEGLView);
	
    CCEGLView::sharedOpenGLView()->setDesignResolutionSize(960, 640, kResolutionShowAll);
    
    // turn on display FPS
    pDirector->setDisplayStats(false);

    // set FPS. the default value is 1.0/60 if you don't call this
    pDirector->setAnimationInterval(1.0 / 60);

    //将数据库复制到可写目录
    string dbSrc = CCFileUtils::sharedFileUtils()->fullPathForFilename(GAME_SYS_DB);
    string dbDes = CCFileUtils::sharedFileUtils()->getWritablePath();
    dbDes.append(GAME_SYS_DB);
    
    if(!OzgFileUtility::fileExists(dbDes))
        OzgFileUtility::copyFile(dbSrc.c_str(), dbDes.c_str());
    CCLog("%s", dbDes.c_str());
    
    //记录检查,如果没有记录则生成
    CppSQLite3DB db;
    db.open(dbDes.c_str());
    
    CppSQLite3Query query = db.execQuery("select count(id) from save_data");
    //    CCLog("%i", query.getIntField(0));
    if(query.getIntField(0) == 0)
        db.execDML(GAME_INIT_SQL);
    
    query.finalize();
    db.close();
    
    //初始化背景音乐和效果音的默认大小值
    SimpleAudioEngine::sharedEngine()->setBackgroundMusicVolume(CCUserDefault::sharedUserDefault()->getFloatForKey(GAME_BG_AUDIO_VOLUME, 1.0));
    SimpleAudioEngine::sharedEngine()->setEffectsVolume(CCUserDefault::sharedUserDefault()->getFloatForKey(GAME_EFFECT_AUDIO_VOLUME, 1.0));
    
    // create a scene. it's an autorelease object
    CCScene *pScene = RPGStartSceneLayer::scene();

    // run
    pDirector->runWithScene(pScene);

    return true;
}
コード例 #12
0
ファイル: DlgEventList.cpp プロジェクト: gaojihao/7520Inspru
void CDlgEventList::ShowPage(int nPageIndex)
{
	CString str;
	int i = 0;
	int nStartIndex = 0;
	int nOffset = 0;

	CppSQLite3DB db;
	db.open(PATH_SQLITE_DB_808);	//打开数据库
	
	//查询记录总数量
	m_nRecordCount = db.execScalar("SELECT count(*) FROM event_info;");
	//计算总页数
	if(m_nRecordCount > 0)
		m_nPageCount = (m_nRecordCount-1)/elist_count+1;
	else
		m_nPageCount = 1;

	//在数据库中查询第nPageIndex页的elist_count条数据
	char szSqlBuffer[512];
	sprintf(szSqlBuffer, "SELECT * FROM event_info ORDER BY event_ID DESC LIMIT %d, %d;", nPageIndex*elist_count, elist_count);
	CppSQLite3Query q = db.execQuery(szSqlBuffer);

	for( i = 0; i < elist_count; i++ )
	{
		if ( !q.eof() )	//数据行
		{
			m_nEvent_ID[i]		= q.getIntField("event_ID");
			m_list[i].chChar	= q.fieldValue("event_content");
			m_list[i].nState	= BTN_STATE_NORMAL;
			q.nextRow();
		}
		else			//空白行
		{
			m_ItemState[i]		= 0;
			m_list[i].chChar	= _T("");
			m_list[i].nState	= BTN_STATE_DISABLE;
		}
	}
	//释放statement
	q.finalize();

	db.close();	//关闭数据库
	return;
}
コード例 #13
0
ファイル: TableBase.cpp プロジェクト: MFDonadeli/PMA
/**
 * Metodo para executar a contagem de registros
 */
long CTableBase::Count(CppSQLite3DB *pDB)
{
	long count = 0;

	CString s = BuildCountQuery();
	CStr s1(s);
	CppSQLite3Query q = pDB->execQuery(s1);
    if(!q.eof())
	{
		TCHAR *endp;
		CString s2(q.fieldValue(0));
		count = _tcstol(s2, &endp, 10);
	}

	q.finalize();

	return count;
}
コード例 #14
0
BOOL CTerminateNewLocationDialog::OnInitDialog() 
{
	CDialog::OnInitDialog();
	
    CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB;
    CppSQLite3Query q = pDB->execQuery("SELECT id,name FROM Locations;");
    //
    while (!q.eof())
    {
        int nIndex = m_ctlLocationList.AddString(q.getStringField("name"));
        m_ctlLocationList.SetItemData(nIndex,q.getIntField("id"));
        q.nextRow();
    }
    q.finalize();
    
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}
コード例 #15
0
void RPGResultsLogic::deductionsItems(CppSQLite3DB *db, int itemsId)
{
    CCString *sql = NULL;
    CppSQLite3Query query = db->execQuery(CCString::createWithFormat(ITEMS_GET, itemsId)->getCString());
    while(!query.eof())
    {
        if(query.getIntField("total") <= 1)
            sql = CCString::createWithFormat(ITEMS_DISCARD, itemsId);
        else
            sql = CCString::createWithFormat(ITEMS_DEDUCTIONS, itemsId);
        
        query.nextRow();
    }
    query.finalize();
    
    if(sql)
        db->execDML(sql->getCString());

}
コード例 #16
0
int RPGResultsLogic::battleSkill(CppSQLite3DB* db, RPGBaseRole* srcObjData, int skillId, RPGBaseRole* targetObjData)
{
    RPGSkill *skill = NULL;
    
    CppSQLite3Query srcSkillQuery = db->execQuery(CCString::createWithFormat(SKILL_DETAIL_QUERY, skillId)->getCString());
    while(!srcSkillQuery.eof())
    {
        skill = RPGSkill::create();
        skill->m_dataId = srcSkillQuery.getIntField("id");
        skill->m_MP = srcSkillQuery.getIntField("mp");
        skill->m_name = srcSkillQuery.getStringField("name_cns");
        skill->m_skillAttack = srcSkillQuery.getFloatField("skill_attack");
        skill->m_attr = srcSkillQuery.getFloatField("attr");
        
        srcSkillQuery.nextRow();
    }
    srcSkillQuery.finalize();
    
    if(skill)
    {
        //扣减MP
        srcObjData->m_MP -= skill->m_MP;
        if(srcObjData->m_MP < 0)
            srcObjData->m_MP = 0;
        
        switch (skill->m_dataId)
        {
            case 2:
                //回复
                return RPGComputingResults::skillCureResults(srcObjData->m_skillAttack, skill->m_skillAttack);
                break;
                
            default:
            {
                //火焰
                int val = RPGComputingResults::skillAttackResults(srcObjData->m_skillAttack, skill->m_skillAttack, (RPGSkillAttr)skill->m_attr, targetObjData->m_skillDefense, kRPGSkillAttrNormal); //后面的参数暂定为普通属性
                return -val;
            }
                break;
        }
    }
    return 0;
}
コード例 #17
0
void CLocationDialog::ReadDB()
{
    m_ctlLocationList.DeleteAllItems();
    //
    //  Read data
    //
    CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB;
    CppSQLite3Query q = pDB->execQuery("select id,name from Locations;");
    //
    while (!q.eof())
    {
        TRACE("%s %s\n",q.fieldValue(0),q.fieldValue(1));
        int nIndex = m_ctlLocationList.InsertItem(1,q.fieldValue(1));
        m_ctlLocationList.SetItemData(nIndex,atoi(q.fieldValue(0)));
        q.nextRow();
    }
    q.finalize();

    m_ctlEditButton.EnableWindow(FALSE);
    m_ctlDeleteButton.EnableWindow(FALSE);
}
コード例 #18
0
RPGMapSceneLayer::~RPGMapSceneLayer()
{
    OzgJoystickLayer *joystick = (OzgJoystickLayer*)this->getChildByTag(kRPGMapSceneLayerTagJoystick);
    joystick->m_target = NULL;
    joystick->inactive();
    
    this->removeAllChildrenWithCleanup(true);
    CCSpriteFrameCache::sharedSpriteFrameCache()->removeSpriteFramesFromFile("joystick.plist");
    
    if(this->m_stringList)
    {
        this->m_stringList->release(); //释放语言数据
        this->m_stringList = NULL;
    }
    
    if(this->m_releaseTexture)
    {
        CCTextureCache::sharedTextureCache()->removeTextureForKey("map.png");
        
        //player部分
        CCTextureCache::sharedTextureCache()->removeTextureForKey("actor4_0.png");
        CCTextureCache::sharedTextureCache()->removeTextureForKey("joystick.png");
        
    }
    
    //数据库部分,释放npc的纹理
    CppSQLite3Query query = this->m_db.execQuery(CCString::createWithFormat(NPC_QUERY, this->m_mapData.mapId)->getCString());
    while(!query.eof())
    {
        CCTextureCache::sharedTextureCache()->removeTextureForKey(query.getStringField("map_texture"));
        query.nextRow();
    }
    query.finalize();
    
//    CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo();
    CCLog("RPGMapSceneLayer 释放");
}
コード例 #19
0
ファイル: DlgAnswerList.cpp プロジェクト: gaojihao/7520Inspru
void    CDlgAnswerList::ShowPage(int nPageIndex)
{
	CString str = _T("");
	int i = 0;
	int nStartIndex = 0;
	int nOffset = 0;
	
	CppSQLite3Table t;
	CppSQLite3Query q;
	CppSQLite3DB db;
	db.open(PATH_SQLITE_DB_808);	//打开数据库
	char szSqlBuffer[1024];
	memset(szSqlBuffer, 0, sizeof(szSqlBuffer));
	//查询记录总数量
// 	sprintf(szSqlBuffer, "SELECT COUNT(*) FROM answer \
// 						 WHERE UID IN (SELECT UID FROM question ORDER BY question_datatime DESC LIMIT %d, 1) \
// 						 ORDER BY answer_ID;", 
// 						 m_nQuestionIndex);
// 	m_nRecordCount = db.execScalar( szSqlBuffer );

	sprintf(szSqlBuffer, "SELECT * FROM answer where UID = '%d';", m_nQuestionIndex);
	t = db.getTable(szSqlBuffer);
	m_nRecordCount = t.numRows();
	
	//计算总页数
	if(m_nRecordCount > 0)
		m_nPageCount = (m_nRecordCount-1)/elist_count+1;
	else
		m_nPageCount = 1;

	memset(szSqlBuffer, 0, sizeof(szSqlBuffer));
	sprintf(szSqlBuffer, "SELECT * FROM question where UID = '%d';", m_nQuestionIndex);
	q = db.execQuery(szSqlBuffer);
	int nFlag = q.getIntField("flag");
	const char* ccText = q.fieldValue("question_content");
	str = ccText;

	//在数据库中查询第nPageIndex页的elist_count条数据
// 	sprintf(szSqlBuffer, "SELECT * FROM answer \
// 						 WHERE UID IN (SELECT UID FROM question ORDER BY question_datatime DESC LIMIT %d, 1) \
// 						 ORDER BY answer_ID LIMIT %d, %d;", 
// 						 m_nQuestionIndex, nPageIndex*elist_count, elist_count);
// 	q = db.execQuery(szSqlBuffer);

	memset(szSqlBuffer, 0, sizeof(szSqlBuffer));
	sprintf(szSqlBuffer, "SELECT * FROM answer where UID = '%d' LIMIT %d, %d;", 
				m_nQuestionIndex, (nPageIndex)*elist_count, elist_count);
	q = db.execQuery(szSqlBuffer);

	for( i = 0; i < elist_count; i++ )
	{
		if ( !q.eof() )	//数据行
		{
			m_nAnswerID[i]		= q.getIntField("answer_ID");
			m_list[i].chChar	= q.fieldValue("answer_content");
			m_list[i].nState	= BTN_STATE_NORMAL;
			q.nextRow();
		}
		else			//空白行
		{
			m_ItemState[i]		= 0;
			m_list[i].chChar	= _T("");
			m_list[i].nState	= BTN_STATE_DISABLE;
		}
	}
	//释放statement
	q.finalize();
	db.close();	//关闭数据库

	if(nFlag)
		TTSSpeaking( str );

	return;
}
コード例 #20
0
ファイル: SetTimeDlg.cpp プロジェクト: xiaoyugm/chtproject
void CSetTimeDlg::OnButSend() 
{
//        swprintf(pTTTW->szText,L"%s",strB); 
 //      swprintf((wchar_t *)pTTTW->szText,L"%s",tooltip.AllocSysString()); 
//			 _stprintf((LPTSTR)word,_T("%s"),strB);  

//	m_ndkSend = new  unsigned char[200]; 
//		GetDlgItem(IDC_COMBO_VERIFYT)->GetWindowText(cccc);
	CString strPointNo,cccc,strim2;
	UpdateData(TRUE);
		GetDlgItem(IDC_COMBO_VERIFYT)->GetWindowText(cccc);
		unsigned char nfds3 = m_Str2Data.String2Int(cccc);
		GetDlgItem(IDC_COMBO_PORT)->GetWindowText(cccc);
		int nfdsP = m_Str2Data.String2Int(cccc);
	unsigned char nfds =nfds3;

	if(chcommand == 0x54)   //校时
	{
//	GetSystemMenu(FALSE)->EnableMenuItem(SC_CLOSE ,MF_DISABLED);
//	GetDlgItem(IDOK_SEND)-> EnableWindow(FALSE);
//	GetDlgItem(IDCANCEL)-> EnableWindow(FALSE);
        m_ndkSend = new  unsigned char[11];
    	CMainFrame* pFWnd=(CMainFrame*)AfxGetMainWnd();
		pFWnd->n_timer60 =1;
	}
	else if(chcommand == 0x4B)            //手动控制
	{
      	m_ndkSend = new  unsigned char[6];
		            m_ndkSend[0] = 0x7E;
		            m_ndkSend[1] = nfds3;
		            m_ndkSend[2] = chcommand;
		            m_ndkSend[3] = nfdsP;
					nfds = m_FUNCTION.GetCurSel();
					if(nfds >1)
					{
          	AfxMessageBox("请选择“吸合”或“断开”!", MB_OK);
			m_FUNCTION.SetCurSel(0);
         	delete m_ndkSend;
			return;
					}
		            m_ndkSend[4] = nfds;
		            m_ndkSend[5] = 0x21;
    	CNDKMessage message1(MANUALCONTROL);
					message1.Add(m_ndkSend , 200);
					theApp.Sync(message1,1);
					if(nfds ==0)
						cccc ="吸合";
					else if(nfds ==1)
						cccc ="断开";

					m_nchangev = chcommand;
        GetDlgItem(IDC_BUT_RES)->ShowWindow(SW_SHOW);
					strim2.Format("%d号分站手动控制:端口%d|%s",nfds3,nfdsP,cccc);
       g_Log.StatusOut(strim2);
	}
	else if(chcommand == 0x43)       //配置测点
	{
        	CString strSQL;
		if(m_SerialF[nfds].SFSd ==0)
		{
        	strSQL.Format("%d号分站没有巡检!",nfds3);
            AfxMessageBox(strSQL, MB_OK);
			return;
		}
      	m_ndkSend = new  unsigned char[166];
		theApp.m_RTDM.SendPP(nfds3);
	}
	else if(chcommand == 0x41)            //配置分站
	{
      	m_ndkSend = new  unsigned char[64];
		int n_fen;
		            m_ndkSend[0] = 0x7E;
		            m_ndkSend[1] = 0x01;
		            m_ndkSend[2] = chcommand;
        for(int nItem=0;nItem<60;nItem++)
		{
    		strPointNo=m_listC.GetItemText(nItem,2);
			n_fen = m_Str2Data.String2Int(strPointNo);
			if(n_fen >99 || n_fen <0)
				break;
			if(n_fen == 0)//输入其它数据时,也是0  重新设为0
	      		m_listC.SetItemText(nItem,2,"0");
              m_ndkSend[nItem+3] = n_fen;
		}
		if(n_fen >99 || n_fen <0)
		{
          	AfxMessageBox("串口号在0-99间选择!", MB_OK);
			m_listC.SetItemText(nItem,2,"0"); //重新设为0
         	delete m_ndkSend;
			return;
		}
		            m_ndkSend[63] = 0x21;
    	CNDKMessage message1(INFODEFINE);
					message1.Add(m_ndkSend , 64);
					theApp.Sync(message1,1);
        for( nItem=0;nItem<60;nItem++)
		{
            				try
							{
                             m_SControl.AbsolutePosition(nItem + 1);
         					 m_SControlNew->m_szSID = nItem+1;
	         				 m_SControlNew->m_szSerialnum = m_ndkSend[nItem+3];
					   	     m_SControlNew->Update();    //Update the recordset
							}
		     			    catch (CAxException *e)
							{
					        	AfxMessageBox(e->m_szErrorDesc, MB_OK);
				        		delete e;
							}
					strPointNo.Format("%d号分站,配串口%d  ",nItem+1,m_ndkSend[nItem+3]);
					strim2 +=strPointNo;
		}//for
		theApp.InitData();
       g_Log.StatusOut("配置分站:" +strim2);
          	AfxMessageBox("配置分站命令发送成功!", MB_OK);
	}
	else if(chcommand == 0x47)            //通讯测试
	{
      	m_ndkSend = new  unsigned char[4];
		            m_ndkSend[0] = 0x7E;
		            m_ndkSend[1] = nfds3;
		            m_ndkSend[2] = chcommand;
		            m_ndkSend[3] = 0x21;
    	CNDKMessage message1(TESTCOMMUNICATION);
					message1.Add(m_ndkSend , 200);
					theApp.Sync(message1,1);
 	  strim2.Format("通讯测试:%d号分站",nfds3);
      g_Log.StatusOut(strim2);
	}
	else if(chcommand == 0x5A)            //故障闭锁
	{
		if(m_SerialF[nfds3].SFSd ==0)
		{
        	strim2.Format("%d号分站没有巡检!",nfds3);
            AfxMessageBox(strim2, MB_OK);
			return;
		}
      	m_ndkSend = new  unsigned char[5];
				    m_ndkSend[0] = 0x7E;
		            m_ndkSend[1] = nfds3;
		            m_ndkSend[2] = chcommand;
					nfds = m_FUNCTION.GetCurSel();
					if(nfds >1)
					{
          	AfxMessageBox("请选择“使能”或“关闭”!", MB_OK);
			m_FUNCTION.SetCurSel(0);
         	delete m_ndkSend;
			return;
					}
		            m_ndkSend[3] = nfds;
		            m_ndkSend[4] = 0x21;
    	CNDKMessage message1(FAULTATRESIA);
					message1.Add(m_ndkSend , 200);
					theApp.Sync(message1,1);
					theApp.n_temp =nfds;

/*            				try
							{
                             m_SControl.AbsolutePosition(m_ndkSend[1]);
         					 m_SControlNew->m_szSID = m_ndkSend[1];
	         				 m_SControlNew->m_szSpeCtrol = (bool)m_ndkSend[3];
					   	     m_SControlNew->Update();    //Update the recordset
							}
		     			    catch (CAxException *e)
							{
					        	AfxMessageBox(e->m_szErrorDesc, MB_OK);
				        		delete e;
							}*/
 	  strim2.Format("%d分站,故障闭锁设为:",nfds3);
			if(nfds ==0)
				strim2 +="关闭";
			else if(nfds ==1)
				strim2 +="使能";
// 	  strim2.Format("%x||%x",nfds3,m_ndkSend[3]);
      g_Log.StatusOut(strim2);
	}
	else if(chcommand == 0x46)            //风电瓦斯闭锁
	{
		if(m_SerialF[nfds3].SFSd ==0)
		{
        	strim2.Format("%d号分站没有巡检!",nfds3);
            AfxMessageBox(strim2, MB_OK);
			return;
		}
		for(int i =0; i < 6 ;i++)//风电瓦斯闭锁关系定义的测点正常时可以初始化、修改
		{
			if(str_list[i].strl =="")
				break;
        	CString strf,strc,strSQL;
		    strf = str_list[i].strl.Mid(0,2);
    		strc = str_list[i].strl.Mid(3,2);
    		int nfds = m_Str2Data.String2Int(strf);
     		int nchan = m_Str2Data.String2Int(strc);
			unsigned char nstatus = m_SlaveStation[nfds][nchan].Channel_state;
			if(nstatus == 0x10 || nstatus == 0x20 || nstatus == 0xa0)
			{
            	strSQL.Format("%d号分站%s状态为%s,不能修改!",nfds,str_list[i].strl,theApp.m_RTDM.strstatus(nstatus));
                AfxMessageBox(strSQL, MB_OK);
	    		return;
			}
		}

      	m_ndkSend = new  unsigned char[10];
		bool b_gas =true;
		            m_ndkSend[0] = 0x7E;
		            m_ndkSend[1] = nfds3;
		            m_ndkSend[2] = chcommand;
        for(int nItem=0;nItem<6;nItem++)
		{
    		strPointNo=m_listC.GetItemText(nItem,2);
			if(strPointNo == "")
			{
				b_gas =false;
				break;
			}
			strPointNo = strPointNo.Mid(3,2);
			nfds = m_Str2Data.String2Int(strPointNo);
	        		m_ndkSend[nItem+3] = nfds;
		}
		if(b_gas)
		{
		            m_ndkSend[9] = 0x21;
                	CNDKMessage message1(WINDGASATRESIA);
					message1.Add(m_ndkSend , 200);
					theApp.Sync(message1,1);

        	for(int i =0;i<6;i++)
        		str_list[i].strl=m_listC.GetItemText(i,2);
        	strim2.Format("设置%d号分站风电瓦斯闭锁:",nfds3);
            AfxMessageBox(strim2);
            g_Log.StatusOut(strim2);
		}
		else
		{
        	delete m_ndkSend;
			strPointNo.Format("第%d项不能为空!",nItem+1);
            AfxMessageBox(strPointNo);
	    	return;
		}
	}
	else if(chcommand == 0xf0)            //双风门、主扇备扇报警
	{
      	m_ndkSend = new  unsigned char[11];
       	LPCTSTR str1 = "",str2 = "",str3 = "";
      	CString  m_strsel,m_strsel2 ,str11,str12;
		int kkk=0;
            				try
							{
         					 m_Fans.m_szFansID = m_nSecond;
							 m_PORT.GetWindowText(m_strsel);
           	m_Str2Data.SplittoCString(m_strsel,str1,str2,str3);
			str11 =str1;
			m_strsel =str2;
			m_strsel +="|";
			m_strsel +=str3;
	         				 m_Fans.m_szName1 = m_strsel;
	         				 m_Fans.m_szpointnum1 = str11 ;
							 m_FUNCTION.GetWindowText(m_strsel2);
           	m_Str2Data.SplittoCString(m_strsel2,str1,str2,str3);
			str12 =str1;
			m_strsel2 =str2;
			m_strsel2 +="|";
			m_strsel2 +=str3;
	         				 m_Fans.m_szName2 = m_strsel2;
	         				 m_Fans.m_szpointnum2 = str12;
				if(str11 == str12)
				{
                 	AfxMessageBox("点号不能相同,请重选!", MB_OK);
                   	delete m_ndkSend;
          			return;
				}
				for ( int i = 0 ; i < m_Records1.size() ; i++ )
				{
    				if((str11 == m_Records1[i])&&(str12 == m_Records2[i]))
					{
						kkk =100;
                    	AfxMessageBox("关联点号已定义,请重选!", MB_OK);
                     	delete m_ndkSend;
           	    		break;
					}
				}
				if(kkk == 100)
           	    		return;

				kkk = m_Records1.size();
				  m_listC.InsertItem(kkk, str11);
    			  m_listC.SetItemText(kkk, 1, m_strsel);
    			  m_listC.SetItemText(kkk, 2, str12);
    			  m_listC.SetItemText(kkk, 3, m_strsel2);
		strim2 = str11 +" "+m_strsel+"   "+str12 + " "+m_strsel2+ "   ";  
            m_strsel.Format(_T("%d态"), m_VERIFYT.GetCurSel());
			strim2 += m_strsel+"   "+theApp.curuser;
    			  m_listC.SetItemText(kkk, 4, m_strsel);
            m_strsel.Format(_T("%d"), m_nSecond);
    			  m_listC.SetItemText(kkk, 5, m_strsel);

				  m_Records1.push_back(str11);
				  m_Records2.push_back(str12);
	
				m_Fans.m_szAStatus = m_VERIFYT.GetCurSel();

      						m_Fans.AddNew();  //Add a new, blank record
					   	    m_Fans.Update();    //Update the recordset
						    m_Fans.Requery();
							m_nSecond++;
							}
		     			    catch (CAxException *e)
							{
					        	AfxMessageBox(e->m_szErrorDesc, MB_OK);
				        		delete e;
							}
		theApp.InitData();

      g_Log.StatusOut("双设备报警关系添加:" +strim2);
	}
	else if(chcommand == 0xf1)            //数据显示页属性
	{
      	m_ndkSend = new  unsigned char[11];
		if(m_nSecond <1)
		{
                 	AfxMessageBox("请选择文件名!", MB_OK);
          			return;
		}
    	CString strPointNo,strrsy,strrsy1,strSQL;
		int ishave=0;
		strrsy1 ="dispoint"+strMetrics;
		strrsy.Format("LP%d",m_nSecond);
		CppSQLite3Query q;
		GetDlgItem(IDC_COMBO_PORT)->GetWindowText(cccc);
//				strSQL.Format("UPDATE '%s' SET LP1='' WHERE DISID =0;",
//					strrsy1);
				strSQL.Format("UPDATE '%s' SET '%s'='%s' WHERE DISID =1;",
					strrsy1,strrsy,cccc);
             q = theApp.db3.execQuery(strSQL);
		GetDlgItem(IDC_COMBO_FUNCTION)->GetWindowText(cccc);

		 if(cccc =="1")
		 {
           for(int m =0; m < 25 ;m++)
		   {
			   if(m < 8)
				strSQL.Format("UPDATE '%s' SET '%s'='%s' WHERE DISID = %d;",
					strrsy1,strrsy,m_listC.GetItemText(m,2),m+11);
			   else
				strSQL.Format("UPDATE '%s' SET '%s'='%s' WHERE DISID = %d;",
					strrsy1,strrsy,m_listC.GetItemText(m,2),m+12);
                q = theApp.db3.execQuery(strSQL);
		   }
		 }
		 else if(cccc =="2")
		 {
           for(int m =0; m < 25 ;m++)
		   {
			   if(m < 8)
				strSQL.Format("UPDATE '%s' SET '%s'='%s' WHERE DISID = %d;",
					strrsy1,strrsy,m_listC.GetItemText(m,2),m+111);
			   else
				strSQL.Format("UPDATE '%s' SET '%s'='%s' WHERE DISID = %d;",
					strrsy1,strrsy,m_listC.GetItemText(m,2),m+112);
             q = theApp.db3.execQuery(strSQL);
		   }
		 }
		 else if(cccc =="3")
		 {
           for(int m =0; m < 25 ;m++)
		   {
			   if(m < 8)
				strSQL.Format("UPDATE '%s' SET '%s'='%s' WHERE DISID = %d;",
					strrsy1,strrsy,m_listC.GetItemText(m,2),m+211);
			   else
				strSQL.Format("UPDATE '%s' SET '%s'='%s' WHERE DISID = %d;",
					strrsy1,strrsy,m_listC.GetItemText(m,2),m+212);
             q = theApp.db3.execQuery(strSQL);
		   }
		 }
    	q.finalize();
       AfxMessageBox("保存成功!", MB_OK);
		m_nchange =1000;
	}
	delete m_ndkSend;
}
コード例 #21
0
ファイル: SetTimeDlg.cpp プロジェクト: xiaoyugm/chtproject
void CSetTimeDlg::OnChCBP() 
{
	UpdateData(TRUE);
		CString cccc;
		GetDlgItem(IDC_COMBO_PORT)->GetWindowText(cccc);
		int nfds3 = m_Str2Data.String2Int(cccc);
	if(chcommand != 0xf1)            //数据显示页属性
	{
		if(nfds3 <1 || nfds3>8)
		{
          	AfxMessageBox("通道号在1-8间选择!", MB_OK);
    		GetDlgItem(IDC_COMBO_PORT)->SetWindowText("1");
	    	  return;
		}
	}
	if(chcommand == 0xf1)            //数据显示页属性
	{
		m_VERIFYT.ResetContent();
    	int  mp = m_PORT.GetCurSel();
		cccc = m_Records1[mp];
//    	GetDlgItem(IDC_COMBO_VERIFYT)->EnableWindow(TRUE);
    	CString strPointNo,strrsy,strrsy1;
    	strrsy = gstrTimeOut + "\\" + strMetrics+ "rsy\\";
		int ishave=0;

		strrsy1 ="dispoint"+strMetrics;
		CppSQLite3Query q;
				strPointNo.Format("select * from '%s' WHERE DISID=1;",strrsy1);
         q = theApp.db3.execQuery(strPointNo);

        for(int k =2; k < 21 ;k++)
		{
            strPointNo = q.getStringField(k);
			strPointNo.TrimRight();
			if(cccc == strPointNo)
			{
				m_nSecond =k-1;
				ishave =k;
	    		cccc.Format("%d",k-1);
    	 	    m_VERIFYT.AddString(cccc);
            	m_VERIFYT.SetCurSel(0);
				break;
			}
		}
		if(ishave == 0)
		{
           for(int k =2; k < 21 ;k++)
		   {
            strPointNo = q.getStringField(k);
			strPointNo.TrimRight();
			if(strPointNo == "")
			{
				m_nSecond =k-1;
	    		cccc.Format("%d",k-1);
    	 	    m_VERIFYT.AddString(cccc);
            	m_VERIFYT.SetCurSel(0);
				break;
			}
		   }
		}
		m_FUNCTION.SetCurSel(0);
//		GetDlgItem(IDC_COMBO_FUNCTION)->GetWindowText(cccc);
//		nfds3 = m_Str2Data.String2Int(cccc);
//		 if(cccc =="1")
//	        m_cChWT.SetCheck(m_Str2Data.String2Int(m_CommonStr[m_ntrans].strc[105+20*(m_nlist-1)]));
         for( k =0; k < 25 ;k++)
		 {
			 if(k < 8)
    			m_listC.SetItemText(k, 2, m_CommonStr[m_nSecond].strc[k+1]);
			 else
    			m_listC.SetItemText(k, 2, m_CommonStr[m_nSecond].strc[k+2]);
		 }
/*		 else if(cccc =="2")
		 strPointNo.Format("select * from '%s' WHERE DISID>110 and DISID<120;",strrsy1);
    				  m_listC.SetItemText(ishave-111, 2, strPointNo);
		 strPointNo.Format("select * from '%s' WHERE DISID>210 and DISID<220;",strrsy1);
    				  m_listC.SetItemText(ishave-211, 2, strPointNo);
		 }*/
		q.finalize();
	}

	UpdateData(FALSE);
}
コード例 #22
0
ファイル: UpdateDlg.cpp プロジェクト: MFDonadeli/PMA
/**
/brief
	Método encarregado de preencher a lista de atualizações a serem feitas, este método escolhe
	quais arquivos irão aparecer nesta lista.
/details
	Faz a leitura do arquivo de atualizações na web e compara a data e hora da lista 
	de arquivos com a tabela de atualizações, se ambas estiverem diferentes a tabela é
	marcada para atualização
/param void
/return void
*/
BOOL CUpdateDlg::_PreencheLista(LPCTSTR szSystem)
{
	CString strSys = szSystem;
	CProcessSystem sys;

	sys.LoadTable(szSystem, &m_tabMap, &m_indexMap);

	try
	{
		if(!CppSQLite3DB::getInstance()->isOpen())
		{
			CppSQLite3DB::getInstance()->open(CStr(m_sPath));
			//CppSQLite3DB::getInstance()->setBusyHandler();
		}
	}
	catch(CppSQLite3Exception e)
	{
		CString msg;
		msg.LoadString(IDS_ERRO_CRIANDO_DB);

		MessageBox(msg, L"Mensagem", MB_ICONINFORMATION|MB_OK);
		STLOG_WRITE("%s(%d): ERRO ABRINDO BANCO DE DADOS %s", __FUNCTION__, __LINE__, e.errorMessage());
		return FALSE;
	}

	m_manageDB->CreateDatabase(&m_tabMap, &m_indexMap);

	//Insert contrato info
	CContratoTable contrato;
	CContratoInfo info;

	info.sCodAutuador = m_params->GetValue(L"cod_autuador");
	info.sContrato = m_params->GetValue(L"contrato");

	if(!info.sCodAutuador.Trim().IsEmpty())
	{
		contrato.Init();
		contrato.SetValues(&info);
		if(!contrato.Insert(CppSQLite3DB::getInstance()))
		{
			STLOG_WRITE("Erro inserindo dados do contrato no database.");
		}
	}

	_FIELDS_ meu_registro;
	CString arquivo, data ,hora;
	int idx = 0;
	TB_ATUALIZACAO *dadoArquivo = NULL;
	CGetFile *m_httpFile;
	m_httpFile = new CGetFile();

	m_httpFile->SetProxy(&m_proxyInfo);
	m_httpFile->SetStructFile(m_sStructPath);

	m_list.ClearBars();
	m_list.DeleteAllItems();
	m_list.UpdateWindow();
	m_httpFile->SetNomeTabela(L"atualizacao");

	CString sContrato = m_params->GetValue(L"contrato");
	CString sURL;
	CString sVarPma = L"transmite_" + strSys;
	
	sURL = m_params->GetValue(sVarPma);
	if(sURL.IsEmpty())
	{
		STLOG_WRITE("CUpdateDlg::_PreencheLista(): url 'transmite_' esta vazia.");
		return FALSE;
	}

	if(! m_httpFile->GetFileFromServer(sURL, sContrato))
	{
		return FALSE;
	}
	int count = 0;

	while(!m_httpFile->IsEOF())
	{
		m_httpFile->GetRecord(&meu_registro);

		meu_registro.Lookup(L"arquivo",arquivo);
		meu_registro.Lookup(L"data",data);
		meu_registro.Lookup(L"hora",hora);

		if(!arquivo.IsEmpty())
		{
			dadoArquivo = new TB_ATUALIZACAO;
			dadoArquivo->nome = arquivo.Trim();
			dadoArquivo->data = data;
			dadoArquivo->hora = hora;

			m_listaArquivos.SetAt(arquivo, dadoArquivo);
		}

		if(!CppSQLite3DB::getInstance()->isOpen())
		{
			idx = m_list.InsertItem(m_list.GetItemCount(), arquivo);
			m_list.CreateProgress(idx, 1);
		}
		else
		{
			//fazer a consulta no banco de dados
			//verificar se a data do record "data" for maior que a data do banco "data_banco"
			//se for, adicona na lista
			CString sQuery;
			sQuery.Format(L"SELECT arquivo FROM atualizacao WHERE "
						  L"arquivo = '%s' AND data = '%s' AND hora = '%s'",
						  arquivo, 
						  data,
						  hora);
			
			try
			{
				ASSERT(CppSQLite3DB::getInstance());
				CppSQLite3Query q = CppSQLite3DB::getInstance()->execQuery(CStr(sQuery));
				if(q.eof())
				{
					idx = m_list.InsertItem(m_list.GetItemCount(), arquivo);
					m_list.CreateProgress(idx, 1);
				}

				q.finalize();
			}
			catch(CppSQLite3Exception e)
			{
				STLOG_WRITE("CUpdateDlg::_PreencheLista(): %s", e.errorMessage());
				STLOG_WRITE(sQuery);
				STLOG_WRITE("----------------------------------------------------------");
				return FALSE;
			}
		}

		m_httpFile->MoveNext();
	}

	delete(m_httpFile);
	m_list.UpdateWindow();
	return TRUE;
}
コード例 #23
0
void BudgetWindow::CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &avg)
{
	if(!cat)
		return;

	BString querystring;
	Fixed cattotal;
	CppSQLite3Query query;

	// find the average amount
	for(int32 j=0; j<gDatabase.CountAccounts(); j++)
	{
		Account *acc = gDatabase.AccountAt(j);
		querystring = "select sum(amount) from account_" ;
		querystring << acc->GetID()	<< " where category = '"
					<< EscapeIllegalCharacters(cat)
					<< "';";
		query = gDatabase.DBQuery(querystring.String(),
								"BudgetWindow::CalcStats:get average");
		cattotal.AddPremultiplied(query.getInt64Field(0));
		query.finalize();
	}
	avg = cattotal;
	avg /= 12;

	// find the highest amount
	cattotal=0;
	for(int32 j=0; j<gDatabase.CountAccounts(); j++)
	{
		Account *acc = gDatabase.AccountAt(j);
		querystring = "select max(amount) from account_" ;
		querystring << acc->GetID()	<< " where category = '"
					<< EscapeIllegalCharacters(cat)
					<< "';";
		query = gDatabase.DBQuery(querystring.String(),
								"BudgetWindow::CalcStats:get highest");
		Fixed value;
		value.SetPremultiplied(query.getInt64Field(0));
		cattotal = MAX(cattotal,value);
		query.finalize();
	}
	high = cattotal;

	// find the lowest amount
	cattotal=0;
	for(int32 j=0; j<gDatabase.CountAccounts(); j++)
	{
		Account *acc = gDatabase.AccountAt(j);
		querystring = "select min(amount) from account_" ;
		querystring << acc->GetID()	<< " where category = '"
					<< EscapeIllegalCharacters(cat)
					<< "';";
		query = gDatabase.DBQuery(querystring.String(),
								"BudgetWindow::CalcStats:get highest");
		Fixed value;
		value.SetPremultiplied(query.getInt64Field(0));
		cattotal = MIN(cattotal,value);
		query.finalize();
	}
	low = cattotal;
}
コード例 #24
0
void BudgetWindow::GenerateBudget(const bool &zero)
{
	// Generate a budget based on the last year's transactions
	ReportGrid income(1,0), spending(1,0);

	gDatabase.DBCommand("delete from budgetlist",
						"BudgetWindow::GenerateBudget:empty budget");

	CppSQLite3Query query;
	query = gDatabase.DBQuery("select * from categorylist order by name",
							"BudgetWindow::GenerateBudget:get categories");

	if(query.eof())
		return;

	float maxwidth=fCategoryList->StringWidth(TRANSLATE("Category"));
	while(!query.eof())
	{
		BString catname = DeescapeIllegalCharacters(query.getStringField(0));

		if(catname.ICompare(TRANSLATE("Transfer"))==0)
		{
			query.nextRow();
			continue;
		}

		bool isexpense = !query.getIntField(1);

		if(isexpense)
		{
			spending.AddItem();
			spending.SetRowTitle(spending.CountItems()-1,catname.String());
		}
		else
		{
			income.AddItem();
			income.SetRowTitle(income.CountItems()-1,catname.String());
		}
		float tempwidth = fCategoryList->StringWidth(catname.String());
		maxwidth = MAX(maxwidth,tempwidth);
		query.nextRow();
	}

	query.finalize();

	// Now that we have the list of categories, query for transactions for each
	// account from each category

	BString querystring;
	Fixed cattotal;
	for(int32 i=0; i<income.CountItems(); i++)
	{
		querystring = "";
		cattotal = 0;

		if(!zero)
		{
			for(int32 j=0; j<gDatabase.CountAccounts(); j++)
			{
				Account *acc = gDatabase.AccountAt(j);
				querystring = "select sum(amount) from account_" ;
				querystring << acc->GetID()	<< " where category = '"
							<< EscapeIllegalCharacters(income.RowTitle(i))
							<< "' and date > " << DecrementDateByYear(GetCurrentDate()) << ";";
				query = gDatabase.DBQuery(querystring.String(),
										"BudgetWindow::GenerateBudget:get category");
				cattotal.AddPremultiplied(query.getInt64Field(0));
				query.finalize();
			}
			cattotal /= 12;
			cattotal.Round();
		}
		income.SetValue(0,i,cattotal);
		gDatabase.AddBudgetEntry(BudgetEntry(income.RowTitle(i),cattotal,BUDGET_MONTHLY,false));
	}

	for(int32 i=0; i<spending.CountItems(); i++)
	{
		querystring = "";
		cattotal = 0;

		if(!zero)
		{
			for(int32 j=0; j<gDatabase.CountAccounts(); j++)
			{
				Account *acc = gDatabase.AccountAt(j);
				querystring = "select sum(amount) from account_" ;
				querystring << acc->GetID()	<< " where category = '"
							<< EscapeIllegalCharacters(spending.RowTitle(i))
							<< "';";
				query = gDatabase.DBQuery(querystring.String(),
										"BudgetWindow::GenerateBudget:get category");
				cattotal.AddPremultiplied(query.getInt64Field(0));
				query.finalize();
			}
			cattotal /= 12;
			cattotal.Round();
		}
		spending.SetValue(0,i,cattotal);
		gDatabase.AddBudgetEntry(BudgetEntry(spending.RowTitle(i),cattotal,BUDGET_MONTHLY,true));
	}
}
コード例 #25
0
//private
void RPGMapSceneLayer::startPlay(float delay)
{
    CCTMXTiledMap *bgMap = (CCTMXTiledMap*)this->getChildByTag(kRPGMapSceneLayerTagBgMap);
    
    //数据库部分,读取npc数据
    CppSQLite3Query query = this->m_db.execQuery(CCString::createWithFormat(NPC_QUERY, this->m_mapData.mapId)->getCString());
    while(!query.eof())
    {
        float x = (stringToNumber<float>(query.getStringField("tmx_x")) + 0.5) * GAME_TMX_ROLE_WIDTH;
        float y = (stringToNumber<float>(query.getStringField("tmx_y")) + 0.5) * GAME_TMX_ROLE_HEIGHT;
        bool autoMove = query.getIntField("auto_move") == 1 ? true : false;
        
        RPGMapNPCRoleSprite *npc = RPGMapNPCRoleSprite::create(query.getIntField("id"), CCString::create(query.getStringField("map_texture")), CCString::create("head_texture"), CCString::create(query.getStringField("name_cns")), CCString::create(query.getStringField("content_cns")), 1, autoMove);
        npc->setTag(kRPGMapSceneLayerTagNPC + query.getIntField("id"));
        npc->setPosition(ccp(x, y));
        bgMap->addChild(npc);
        
        query.nextRow();
    }
    query.finalize();
    
    //player
    int defaultSpriteFrameIndex = 1; //默认为向下
    if(this->m_mapData.playerDirection.compare("up") == 0)
    {
        defaultSpriteFrameIndex = 10;
    }
    else if(this->m_mapData.playerDirection.compare("left") == 0)
    {
        defaultSpriteFrameIndex = 4;
    }
    else if(this->m_mapData.playerDirection.compare("right") == 0)
    {
        defaultSpriteFrameIndex = 7;
    }
    RPGMapRoleSprite *player = RPGMapRoleSprite::create(CCString::create("actor4_0.png"), CCString::create("Player"), true, defaultSpriteFrameIndex);
    player->setPosition(ccp(this->m_mapData.playerToX * GAME_TMX_ROLE_WIDTH, this->m_mapData.playerToY * GAME_TMX_ROLE_HEIGHT));
    player->setTag(kRPGMapSceneLayerTagPlayer);
    player->m_type = kRPGMapRoleSpriteTypePlayer;
    bgMap->addChild(player);
    
    CCSprite *spJoystick = CCSprite::createWithSpriteFrameName("Ball.png");
    CCSprite *joystickBg = CCSprite::createWithSpriteFrameName("Dock.png");
    OzgJoystickLayer *joystick = OzgJoystickLayer::layerActivityJoystick(50, spJoystick, joystickBg, false);
    joystick->setTag(kRPGMapSceneLayerTagJoystick);
    joystick->m_target = this;
    joystick->m_endedSelector = callfunc_selector(RPGMapSceneLayer::joystickEndedFunc);
    this->addChild(joystick);
    
    //menu
    CCMenu *mainMenu = CCMenu::create();
    mainMenu->setTag(kRPGMapSceneLayerTagMainMenu);
    mainMenu->setAnchorPoint(ccp(0.5, 0.5));
    mainMenu->setPosition(CCPointZero);
    mainMenu->setContentSize(bgMap->getContentSize());
    bgMap->addChild(mainMenu);

    CCMenuItemSprite *menuCommand = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("commons_btn_back_04.png"), CCSprite::createWithSpriteFrameName("commons_btn_back_04.png"), this, menu_selector(RPGMapSceneLayer::onMenu));
    menuCommand->setPosition(ccp(mainMenu->getContentSize().width - 35, mainMenu->getContentSize().height - 35));
    menuCommand->setTag(kRPGMapSceneLayerTagMainMenuCommand);
    menuCommand->setRotation(180);
    menuCommand->setScale(0.75);
    mainMenu->addChild(menuCommand);

//    CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo();
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 1, true);
    this->scheduleUpdate();
    
}
コード例 #26
0
ファイル: RCGen.cpp プロジェクト: MFDonadeli/PMA
void CRcGen::Init(BOOL bUp)
{
	m_ResTable.Init(L"RES");
	CStringA sQuery;

	if(arrControles.GetSize() > 0)
	{
		_deleteArrControles();
	}

	m_nIdInicial = -1;

	_SetMaxY();
	m_nCtrl=0;
	m_nXCol=0;
	
	m_pDB = CppSQLite3DB::getInstance();
	CppSQLite3Query q;

	try
	{
	#ifdef _WIN32_WCE
		sQuery.Format("select * from res where grupo = %d", m_nGrupo);
	#else
		sQuery.Format("select * from res where grupo = %d", m_nGrupo);
	#endif
		//sQuery.Format("select * from res where id BETWEEN %d AND %d and grupo = %d", nCtrl+1, nCtrl+10, nGrupo);
		q = m_pDB->execQuery(sQuery); 

		if(!q.eof())
		{
			m_nGrupo = q.getIntField("Grupo");
		}

		while(!q.eof())
		{
			cControles cCtrl;
			
			cCtrl.nID = q.getIntField("ID");
			cCtrl.sTipo = q.getStringField("Tipo"); 
			cCtrl.iLargura = q.getIntField("Largura"); 
			cCtrl.iPagina = q.getIntField("Pagina"); 
			cCtrl.sNome = q.getStringField("Nome"); 
			cCtrl.sID = q.getStringField("IDStr"); 
			cCtrl.sDBRef.Format(L"%S.%S", q.getStringField("DBRef"), q.getStringField("DBFieldRef"));
			cCtrl.iSizeDb = q.getIntField("TamanhoCampo"); 
			cCtrl.sFill = q.getStringField("FillFrom"); 
			cCtrl.iExCtrl = q.getIntField("IsEx"); 
			cCtrl.iManterLinha = q.getIntField("Quebrar"); 
			cCtrl.iDesabilitado = q.getIntField("Desabilitar"); 
			cCtrl.iReadOnly = q.getIntField("Leitura"); 
			cCtrl.iObrigatorio = q.getIntField("Obrigatorio"); 			
			cCtrl.iGrupo = q.getIntField("Grupo"); 
			cCtrl.iSubGrupo = q.getIntField("SubGrupo");
			cCtrl.iLinhas = q.getIntField("Linhas");
			cCtrl.sBDValue = q.getStringField("BDValue");
			cCtrl.iAgrupado = q.getIntField("Agrupado");
			cCtrl.iTopo = q.getIntField("Topo");
			cCtrl.iEsquerda = q.getIntField("Esquerda");
			cCtrl.iAltura = q.getIntField("Altura");

			arrControles.Add(cCtrl);

			q.nextRow();

		}

		q.finalize();

	}
	catch(CppSQLite3Exception e)
	{
		
	}

	m_y=DEFAULT_Y_INIT;
	m_x=0;
	m_nSubGrupo=0;
}
コード例 #27
0
BOOL CEditTrainDialog::OnInitDialog() 
{
	CDialog::OnInitDialog();
	
	// TODO: Add extra initialization here
	
    m_ctlIndustryList.InsertColumn(0,"");
    m_ctlIndustryList.SetColumnWidth(0,186);
    m_ctlIndustryList.SetExtendedStyle(m_ctlIndustryList.GetExtendedStyle()|LVS_EX_CHECKBOXES);

    CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB;
    //
    //  create and preload _TL and _TI
    //
    //try { pDB->execDML("DROP TABLE _TL;"); } catch (...) {}
    //try { pDB->execDML("DROP TABLE _TI;"); } catch (...) {}
    CString sSQL;
    sSQL.Format("CREATE TEMP TABLE _TL AS SELECT * FROM Trains_Location WHERE Train_FK=%d;",m_iTrainID);
    pDB->execDML(sSQL);
    sSQL.Format("CREATE TEMP TABLE _TI AS SELECT * FROM Trains_Industry WHERE Train_FK=%d;",m_iTrainID);
    pDB->execDML(sSQL);
    //
    CppSQLite3Query q = pDB->execQuery("SELECT id,name FROM Locations;");
    //
    while (!q.eof())
    {
        int nIndex = m_ctlLocationList.AddString(q.fieldValue(1));
        m_ctlLocationList.SetItemData(nIndex,atoi(q.fieldValue(0)));
        q.nextRow();
    }
    q.finalize();
    sSQL.Format("SELECT name,trainid FROM Trains WHERE id=%d",m_iTrainID);
    q = pDB->execQuery(sSQL);
    if (!q.eof())
    {
        m_sTrainName = q.getStringField(0);
        m_sTrainCode = q.getStringField(1);
    }
    else
    {
        m_sTrainName = "Un-named Train";
        m_sTrainCode = "ZZZZ";
    }
    q.finalize();
    //
    //  get current locations
    //
    sSQL.Format("SELECT Trains_Location.Location_FK,Locations.name FROM Trains_Location, Locations WHERE Train_FK=%d AND Locations.id = Trains_Location.Location_FK ORDER BY route_order",m_iTrainID);
    q = pDB->execQuery(sSQL);
    while (!q.eof())
    {
        int nIndex = m_ctlRouteLocationList.AddString(q.getStringField("name"));
        m_ctlRouteLocationList.SetItemData(nIndex,q.getIntField("Location_FK"));
        //
        q.nextRow();
    }
    q.finalize();
    //
	m_ctlRemoveButton.EnableWindow(FALSE);
	m_ctlIndustryList.EnableWindow(FALSE);
	m_ctlLocalSwitcher.EnableWindow(FALSE);
	m_ctlDown.EnableWindow(FALSE);
	m_ctlUp.EnableWindow(FALSE);
    m_ctlAddButton.EnableWindow(FALSE);
    m_ctlMaxMovesText.EnableWindow(FALSE);
    m_ctlMaxMoves.EnableWindow(FALSE);
    //
    UpdateData(FALSE);
    //
    return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}
コード例 #28
0
void CEditTrainDialog::OnSelchangeRoutelocationlist() 
{
	// TODO: Add your control notification handler code here
    if( m_ctlRouteLocationList.GetCurSel() == -1 )
    {
    	m_ctlRemoveButton.EnableWindow(FALSE);
	    m_ctlIndustryList.EnableWindow(FALSE);
    	m_ctlLocalSwitcher.EnableWindow(FALSE);
    	m_ctlDown.EnableWindow(FALSE);
	    m_ctlUp.EnableWindow(FALSE);
        m_ctlMaxMovesText.EnableWindow(FALSE);
        m_ctlMaxMoves.EnableWindow(FALSE);
    }
    else
    {
    	m_ctlRemoveButton.EnableWindow(TRUE);
	    m_ctlIndustryList.EnableWindow(TRUE);
	    m_ctlLocalSwitcher.EnableWindow(TRUE);
    	m_ctlDown.EnableWindow(TRUE);
	    m_ctlUp.EnableWindow(TRUE);
        m_ctlMaxMovesText.EnableWindow(TRUE);
        m_ctlMaxMoves.EnableWindow(TRUE);
        //
        //  read DB for this item
        //
        int iLocationID = m_ctlRouteLocationList.GetItemData(m_ctlRouteLocationList.GetCurSel());
        CString sSQL;
        sSQL.Format("SELECT Industries.id,Industries.name FROM Industries,Sidings WHERE Industries.Sidings_FK=Sidings.id AND Sidings.Locations_FK=%d",iLocationID);
        CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB;
        CppSQLite3Query q = pDB->execQuery(sSQL);
        //
        m_ctlIndustryList.DeleteAllItems();
      	m_bLocalSwitcher = FALSE;
        while (!q.eof())
        {
            int nIndex = m_ctlIndustryList.InsertItem(1,q.getStringField("name"));
            m_ctlIndustryList.SetItemData(nIndex,q.getIntField("id"));
            //
            //  see if this industry is served by this train
            //
            sSQL.Format("SELECT 1 FROM _TI WHERE Industry_FK=%d",q.getIntField("id"));
            CppSQLite3Query q2 = pDB->execQuery(sSQL);
            BOOL bCheck = FALSE;
            if( !q2.eof() )
                bCheck = TRUE;
            q2.finalize();
            if( bCheck )
                m_ctlIndustryList.SetCheck(nIndex,TRUE);
            //
            q.nextRow();
        }
        q.finalize();
        //
        //  check for local switcher for this location
        //
        sSQL.Format("SELECT localswitcher FROM _TL WHERE Location_FK=%d;",iLocationID);
        q = pDB->execQuery(sSQL);
        if( !q.eof() )
        {
            if( q.getIntField("localswitcher") == 1 )
                m_bLocalSwitcher = TRUE;
        }
        q.finalize();
        //
        //  check for limited moves
        //
        sSQL.Format("SELECT max_moves FROM _TL WHERE Location_FK=%d;",iLocationID);
        q = pDB->execQuery(sSQL);
        if( !q.eof() )
        {
            if( q.getIntField("max_moves") > 0 )
                m_iMaxMoves = q.getIntField("max_moves");
            else
                m_iMaxMoves = 0;
        }
        q.finalize();
        //
        sSQL.Format("SELECT 1 FROM Sidings WHERE Sidings.Locations_FK=%d AND interchange=1",iLocationID);
        q = pDB->execQuery(sSQL);
        if( !q.eof() )
        {
            m_ctlSwitchInterchanges.EnableWindow(TRUE);
            sSQL.Format("SELECT switch_interchanges FROM _TL WHERE Location_FK=%d;",iLocationID);
            CppSQLite3Query q2 = pDB->execQuery(sSQL);
            if( !q2.eof() )
            {
                int iSwitch = q2.getIntField("switch_interchanges");
                m_bSwitchInterchanges = iSwitch==1?TRUE:FALSE;
            }
            q2.finalize();
        }
        else
        {
            m_ctlSwitchInterchanges.EnableWindow(FALSE);
            m_bSwitchInterchanges = FALSE;
        }
        q.finalize();
    }
    UpdateData(FALSE);
    if( m_bLocalSwitcher )
        m_ctlIndustryList.EnableWindow(FALSE);
    else
        m_ctlIndustryList.EnableWindow(TRUE);
}
コード例 #29
0
void CEditTrainDialog::OnOK() 
{
	// TODO: Add extra validation here
    //
    //  insert into Trains_Location / Trains_Industry
    //  (see code in OnCreateButton below)
    //

    UpdateData();
    //
    CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB;
    //
    if( m_iTrainID == -1 )
    {
        //
        //  Convert to Trains, Train_Location, and Train_Industry tables
        //
        //  If there are not any industries checked, AND there isnt a local switcher checked,
        //  we make a location/location/location route.  If there are industries checked, its
        //  an industry-based checklist.  All the same to the program, different for the user
        //
        //  First, create Train table entry, and get the ID
        //
        CString sSQL;
        sSQL.Format("INSERT INTO Trains (trainid,name,Route_FK) VALUES (\"%s\",\"%s\",-1);",m_sTrainCode,m_sTrainName);
        try {
            pDB->execDML(sSQL);
        }
        catch (...)
        {
            sSQL.Format("INSERT INTO Trains (trainid,name) VALUES (\"%s\",\"%s\");",m_sTrainCode,m_sTrainName);
            pDB->execDML(sSQL);
        }
        //
        sSQL = "SELECT last_insert_rowid()";
        CppSQLite3Query q = pDB->execQuery(sSQL);   
        int iTrainID = atoi(q.fieldValue(0));
        q.finalize();
        //
        //  update _TL and _TI with train ID
        //
        sSQL.Format("UPDATE _TI SET Train_FK=%d;",iTrainID);
        pDB->execDML(sSQL);
        pDB->execDML("INSERT INTO Trains_Industry SELECT * FROM _TI");
        //
        //  Put entries into Train_Location table
        //
        for( int i=0;i<m_ctlRouteLocationList.GetCount();i++ )
        {
            int iLocationID = m_ctlRouteLocationList.GetItemData(i);
            //
            //  local switcher and switch_interchanges for this location
            //
            sSQL.Format("SELECT localswitcher,switch_interchanges,max_moves FROM _TL WHERE Location_FK=%d;",iLocationID);
            CppSQLite3Query q = pDB->execQuery(sSQL);
            int iLocalSwitcher(0);
            int iSwitchInterchanges(1);
            int iMaxMoves(0);
            if( !q.eof())
            {
                iLocalSwitcher = q.getIntField("localswitcher");
                iSwitchInterchanges = q.getIntField("switch_interchanges");
                iMaxMoves = q.getIntField("max_moves");
            }
            q.finalize();
            //
            sSQL.Format("INSERT INTO Trains_Location (Train_FK,route_order,Location_FK,localswitcher,switch_interchanges,max_moves) VALUES (%d,%d,%d,%d,%d,%d);",iTrainID,i+1,iLocationID,iLocalSwitcher,iSwitchInterchanges,iMaxMoves);
            pDB->execDML(sSQL);
        }
        //
        //MessageBox("Train Created!");
    }
    else
    {
        //
        //  Delete existing Train_Location and Train_Industry entries for this train
        //
        CString sSQL;
        sSQL.Format("DELETE FROM Trains_Location WHERE Train_FK=%d;",m_iTrainID);
        pDB->execDML(sSQL);
        sSQL.Format("DELETE FROM Trains_Industry WHERE Train_FK=%d;",m_iTrainID);
        pDB->execDML(sSQL);
        //
        //  Update Routes name and code
        //
        sSQL.Format("UPDATE Trains SET trainid=\"%s\" ,name=\"%s\" WHERE id=%d;",m_sTrainCode,m_sTrainName,m_iTrainID);
        pDB->execDML(sSQL);
        //
        //  Put entries into Trains_Location and Trains_Industry tables
        //
        pDB->execDML("INSERT INTO Trains_Industry SELECT * FROM _TI");
        //
        for( int i=0;i<m_ctlRouteLocationList.GetCount();i++ )
        {
            int iLocationID = m_ctlRouteLocationList.GetItemData(i);
            //
            //  local switcher and switch interchanges for this location?
            //
            sSQL.Format("SELECT localswitcher,switch_interchanges,max_moves FROM _TL WHERE Location_FK=%d;",iLocationID);
            CppSQLite3Query q = pDB->execQuery(sSQL);
            int iLocalSwitcher(0);
            int iSwitchInterchanges(1);
            int iMaxMoves(0);
            if( !q.eof())
            {
                iLocalSwitcher = q.getIntField("localswitcher");
                iSwitchInterchanges = q.getIntField("switch_interchanges");
                iMaxMoves = q.getIntField("max_moves");
            }
            q.finalize();
            //
            sSQL.Format("INSERT INTO Trains_Location (Train_FK,route_order,Location_FK,localswitcher,switch_interchanges,max_moves) VALUES (%d,%d,%d,%d,%d,%d);",m_iTrainID,i+1,iLocationID,iLocalSwitcher,iSwitchInterchanges,iMaxMoves);
            pDB->execDML(sSQL);
        }
        //
        MessageBox("Train Updated!");
    }
    //
    try { pDB->execDML("DROP TABLE _TL;"); } catch (...) {}
    try { pDB->execDML("DROP TABLE _TI;"); } catch (...) {}
	CDialog::OnOK();
}
コード例 #30
0
int main(int argc, char** argv)
{
    try
    {
        int i, fld;
        time_t tmStart, tmEnd;
        CppSQLite3DB db;

        cout << "SQLite Header Version: " << CppSQLite3DB::SQLiteHeaderVersion() << endl;
        cout << "SQLite Library Version: " << CppSQLite3DB::SQLiteLibraryVersion() << endl;
        cout << "SQLite Library Version Number: " << CppSQLite3DB::SQLiteLibraryVersionNumber() << endl;

        remove(gszFile);
        db.open(gszFile);

        cout << endl << "emp table exists=" << (db.tableExists("emp") ? "TRUE":"FALSE") << endl;
        cout << endl << "Creating emp table" << endl;
        db.execDML("create table emp(empno int, empname char(20));");
        cout << endl << "emp table exists=" << (db.tableExists("emp") ? "TRUE":"FALSE") << endl;
        ////////////////////////////////////////////////////////////////////////////////
        // Execute some DML, and print number of rows affected by each one
        ////////////////////////////////////////////////////////////////////////////////
        cout << endl << "DML tests" << endl;
        int nRows = db.execDML("insert into emp values (7, 'David Beckham');");
        cout << nRows << " rows inserted" << endl;

        nRows = db.execDML("update emp set empname = 'Christiano Ronaldo' where empno = 7;");
        cout << nRows << " rows updated" << endl;

        nRows = db.execDML("delete from emp where empno = 7;");
        cout << nRows << " rows deleted" << endl;

        ////////////////////////////////////////////////////////////////////////////////
        // Transaction Demo
        // The transaction could just as easily have been rolled back
        ////////////////////////////////////////////////////////////////////////////////
        int nRowsToCreate(25000);
        cout << endl << "Transaction test, creating " << nRowsToCreate;
        cout << " rows please wait..." << endl;
        tmStart = time(0);
		cout << "PRE-TXN AUTO COMMIT=" << (db.IsAutoCommitOn() ? "Y" : "N") << endl;
        db.execDML("begin transaction;");
		cout << "IN-TXN AUTO COMMIT=" << (db.IsAutoCommitOn() ? "Y" : "N") << endl;

        for (i = 0; i < nRowsToCreate; i++)
        {
            char buf[128];
            sprintf(buf, "insert into emp values (%d, 'Empname%06d');", i, i);
            db.execDML(buf);
        }

        db.execDML("commit transaction;");
		cout << "POST-TXN AUTO COMMIT=" << (db.IsAutoCommitOn() ? "Y" : "N") << endl;
        tmEnd = time(0);

        ////////////////////////////////////////////////////////////////////////////////
        // Demonstrate CppSQLiteDB::execScalar()
        ////////////////////////////////////////////////////////////////////////////////
        cout << db.execScalar("select count(*) from emp;") << " rows in emp table in ";
        cout << tmEnd-tmStart << " seconds (that was fast!)" << endl;

        ////////////////////////////////////////////////////////////////////////////////
        // Re-create emp table with auto-increment field
        ////////////////////////////////////////////////////////////////////////////////
        cout << endl << "Auto increment test" << endl;
        db.execDML("drop table emp;");
        db.execDML("create table emp(empno integer primary key, empname char(20));");
        cout << nRows << " rows deleted" << endl;

        for (i = 0; i < 5; i++)
        {
            char buf[128];
            sprintf(buf, "insert into emp (empname) values ('Empname%06d');", i+1);
            db.execDML(buf);
            cout << " primary key: " << (int)db.lastRowId() << endl;
        }

        ////////////////////////////////////////////////////////////////////////////////
        // Query data and also show results of inserts into auto-increment field
        ////////////////////////////////////////////////////////////////////////////////
        cout << endl << "Select statement test" << endl;
        CppSQLite3Query q = db.execQuery("select * from emp order by 1;");

        for (fld = 0; fld < q.numFields(); fld++)
        {
            cout << q.fieldName(fld) << "(" << q.fieldDeclType(fld) << ")|";
        }
        cout << endl;

        while (!q.eof())
        {
            cout << q.fieldValue(0) << "|";
            cout << q.fieldValue(1) << "|" << endl;
            q.nextRow();
        }


        ////////////////////////////////////////////////////////////////////////////////
        // SQLite's printf() functionality. Handles embedded quotes and NULLs
        ////////////////////////////////////////////////////////////////////////////////
        cout << endl << "SQLite sprintf test" << endl;
        CppSQLite3Buffer bufSQL;
        bufSQL.format("insert into emp (empname) values (%Q);", "He's bad");
        cout << (const char*)bufSQL << endl;
        db.execDML(bufSQL);

        bufSQL.format("insert into emp (empname) values (%Q);", NULL);
        cout << (const char*)bufSQL << endl;
        db.execDML(bufSQL);

        ////////////////////////////////////////////////////////////////////////////////
        // Fetch table at once, and also show how to use CppSQLiteTable::setRow() method
        ////////////////////////////////////////////////////////////////////////////////
        cout << endl << "getTable() test" << endl;
        CppSQLite3Table t = db.getTable("select * from emp order by 1;");

        for (fld = 0; fld < t.numFields(); fld++)
        {
            cout << t.fieldName(fld) << "|";
        }
        cout << endl;
        for (int row = 0; row < t.numRows(); row++)
        {
            t.setRow(row);
            for (int fld = 0; fld < t.numFields(); fld++)
            {
                if (!t.fieldIsNull(fld))
                    cout << t.fieldValue(fld) << "|";
                else
                    cout << "NULL" << "|";
            }
            cout << endl;
        }


        ////////////////////////////////////////////////////////////////////////////////
        // Test CppSQLiteBinary by storing/retrieving some binary data, checking
        // it afterwards to make sure it is the same
        ////////////////////////////////////////////////////////////////////////////////
        cout << endl << "Binary data test" << endl;
        db.execDML("create table bindata(desc char(10), data blob);");
        
        unsigned char bin[256];
        CppSQLite3Binary blob;

        for (i = 0; i < sizeof bin; i++)
        {
            bin[i] = i;
        }

        blob.setBinary(bin, sizeof bin);

        bufSQL.format("insert into bindata values ('testing', %Q);", blob.getEncoded());
        db.execDML(bufSQL);
        cout << "Stored binary Length: " << sizeof bin << endl;

        q = db.execQuery("select data from bindata where desc = 'testing';");

        if (!q.eof())
        {
            blob.setEncoded((unsigned char*)q.fieldValue("data"));
            cout << "Retrieved binary Length: " << blob.getBinaryLength() << endl;
        }
		q.finalize();

        const unsigned char* pbin = blob.getBinary();
        for (i = 0; i < sizeof bin; i++)
        {
            if (pbin[i] != i)
            {
                cout << "Problem: i: ," << i << " bin[i]: " << pbin[i] << endl;
            }
        }


		////////////////////////////////////////////////////////////////////////////////
        // Pre-compiled Statements Demo
        ////////////////////////////////////////////////////////////////////////////////
        cout << endl << "Transaction test, creating " << nRowsToCreate*2;
        cout << " rows please wait..." << endl;
        db.execDML("drop table emp;");
        db.execDML("create table emp(empno int, empname char(20));");
        tmStart = time(0);
        db.execDML("begin transaction;");

        cout << endl << "Creating with bind by number" << endl;
        CppSQLite3Statement stmt = db.compileStatement("insert into emp values (?, ?);");
        for (i = 0; i < nRowsToCreate; i++)
        {
            char buf[16];
            sprintf(buf, "EmpName%06d", i);
            stmt.bind(1, i);
            stmt.bind(2, buf);
            stmt.execDML();
            stmt.reset();
        }

        cout << endl << "Creating with bind by name" << endl;
		CppSQLite3Statement stmt2 = db.compileStatement("insert into emp values (:p1, @p2);");
        for (i = 0; i < nRowsToCreate; i++)
        {
            char buf[16];
            sprintf(buf, "EmpName%06d", i);
			stmt2.bind(":p1", i);
			stmt2.bind("@p2", buf);
            stmt2.execDML();
            stmt2.reset();
        }

		db.execDML("commit transaction;");
        tmEnd = time(0);

        cout << db.execScalar("select count(*) from emp;") << " rows in emp table in ";
        cout << tmEnd-tmStart << " seconds (that was even faster!)" << endl;
        cout << endl << "End of tests" << endl;
    }
    catch (CppSQLite3Exception& e)
    {
        cerr << e.errorCode() << ":" << e.errorMessage() << endl;
    }

    ////////////////////////////////////////////////////////////////////////////////
    // Loop until user enters q or Q
    ////////////////////////////////////////////////////////////////////////////////
    char c(' ');

    while (c != 'q' && c != 'Q')
    {
        cout << "Press q then enter to quit: ";
        cin >> c;
    }
    return 0;
}