Tải bản đầy đủ - 0 (trang)
Hack 7. Rid Your Database of Clutter

Hack 7. Rid Your Database of Clutter

Tải bản đầy đủ - 0trang

needtocreatealogtabletostoretheobjectnames.This

doesn'tneedtobefancy;indeed,thelogtablecanhavejusta

singlefieldtostorethenames.Optionalfieldscanstorea

timestamp,thetypeofobject,andsoforth.

Figure1-15showsthedesignofsuchatable.Itcomprisestwo

fields:onecapturestheobjectname,andtheothercaptures

theobjecttype.Thetablereceivesarecordeachtimeanobject

isopened.

Toappendarecordtothelogtable,anobjectmusthavealittle

bitofcodeinitsopenevent.Hereisasnippetthatwouldgo

intotheopeneventofaformnamedCustomers:



PrivateSubForm_Open(CancelAsInteger)

DimconnAsADODB.Connection

Setconn=CurrentProject.Connection

DimssqlAsString

ssql="InsertIntotblObjectLogValues('Customers','Fo

conn.Executessql

conn.Close

Setconn=Nothing

EndSub



Figure1-15.Atableforloggingobjectsasthey

areopened



Whentheformisopened,arecordiswrittenintothelogwith

theform'snameandobjecttype.Youshouldputsimilarcode

intotheopeneventofallformsandreports.Thenletyourusers

usethedatabaseagain,andwatchthelogtablebegintofillup.

Afterareasonableamountoftimeaweek,amonth,whatever

makessenseexaminethelogtable.Youwillseenumerous

entries.Ifatimestampfieldwasnotused,youwillseequitea

numberofduplicaterecords.UseaSelectquerywithaGroupBy

aggregateclausetoviewtheresultswithoutseeingduplicates.



1.8.2.IdentifyingUnusedObjects

Figure1-16displaysaqueryoftheObjectlogtable.Thelisted

objectsrepresentthedefinitivelistofobjectsusersareopening.

Youcancomparethislisttothefulllistofformsandreportsin

thedatabase,andyoucansafelydeletetheformsandreports



thataren'tonthelistaslongasyou'recomfortablethatenough

timehaspassed.Don'tforgettocompactthedatabaseafter

deletingtheobjects!



Figure1-16.Reviewinguseddatabaseobjects



1.8.3.HackingtheHack

Partofthishackconcernsthenecessitytoaddcodetothe

openingroutineofalltheformsandreports.Whatamanual

hassle!However,youcanautomatethistask.Hereisan

exampleofcodethatupdatestheopeneventsofallthereports

inthedatabase:

PublicSubinsert_open_report_event()

'!!Makesureallreportsareclosedbeforerunning!!

DimrptAsAccessObject

ForEachrptInCurrentProject.AllReports

DoCmd.OpenReportrpt.Name,acViewDesign



WithReports(0).Module

OnErrorResumeNext

open_proc_start=.ProcBodyLine("Report_Open",vbext

IfError<>0Then

'hasnoopenevent,socreateone

Err.Clear

open_proc_start=.CreateEventProc("Open","Repor

EndIf

.InsertLinesopen_proc_start+1,_

"DimconnasADODB.Connection"

.InsertLinesopen_proc_start+2,_

"Setconn=CurrentProject.Connection"

.InsertLinesopen_proc_start+3,_

"DimssqlasString"

.InsertLinesopen_proc_start+4,_

"ssql=""InsertIntotblObjectLogValues('"&_

Reports(0).Name&"','Report')"""

.InsertLinesopen_proc_start+5,_

"conn.Executessql"

.InsertLinesopen_proc_start+6,_

"conn.Close"

.InsertLinesopen_proc_start+7,_

"Setconn=Nothing"

EndWith

DoCmd.CloseacReport,Reports(0).Name,acSaveYes

Next

MsgBox"AllReportsUpdated"

EndSub



Thiscoderoutineworkswiththemodulebehindthereport.This

isactualVBAthatwritesVBAkindaneat!Basically,eachreport

isopenedinDesignmode;codeistheninsertedintothe

report'scodemodule.Youcandevelopasimilarroutinetowork

withforms,too;you'llneedtoaddresstheAllFormscollection

insteadoftheAllReportscollection.



Hack8.ProtectValuableInformation



Protectyourdatausingtheread-onlycommand-line

switchsothatuserscan'teditthedata.

Creatingadesktopshortcuttoadatabaseprovidesabehindthe-scenesbenefit.Specifically,youcanusecommand-line

switchesthatareunseenbyallbutthetechnicallycurious.

Inthismanner,itiseasytosetupashortcuttoopena

databaseinread-onlymodeand,thusprotectyourdataand

designelements.Todothis,addthe/roswitchattheendofthe

targetstringinthedesktopshortcut.Notethatthefulltarget

stringisn'tjustthepathtothedatabase;itneedstostartwith

thepathtotheAccessexecutable,followedbythedatabase

path,followedbytheswitch.

UsingAccess2003,whichbydefaultisinthestandardProgram

Files/MicrosoftOffice/Office11directory,thefulltargetstring

lookslikethis:







"C:\ProgramFiles\MicrosoftOffice\OFFICE11\MSACCESS.EX

"C:\SalesSummaries\Sales2005.mdb"/ro



Whenthedesktopshortcutisclicked,thedatabaseopensin

read-onlymode.Aconfirmationmessageispresentedat

startup,showninFigure1-17.Datacan'tbeadded,deleted,or

edited.

Thisisagreatwaytodisseminateinformationwithoutconcern

fordataintegrityissues.Distributingthedatabaseapplicationin

suchawaythatadesktopshortcutiscreatedorupdated



guaranteesthatthedatabaseopensinjustthewayyou

intended.



Figure1-17.Areminderabouttheread-only

status



1.9.1.ButJustinCase

Ofcourse,ahalf-savvyusercanjuststartupAccessandopen

thedatabaseviatheOpendialog,thusbypassingthedesktop

shortcut.Thedatabaseisthenopenedinfullread/writemode,

unlessagotchaisinplacetopreventthis.

Tohandlethis,youcanplaceasimpleSQLInsertoperationin

thedatabase'sopeningroutine,andyoucanincludeanextra

tableinthedatabaseforjustthispurpose.Iftheoperation

succeeds,theuseriswarnedtousethedesktopshortcut(as

showninFigure1-18),andthedatabasecloses.



Figure1-18.Catchinguserswhotrytoskipusing

thedesktopshortcut



1.9.2.TheCode

Here'stheroutinethattestsaSQLInsert:





PublicFunctiontest_mode()

OnErrorGoToerr_end



DimconnAsADODB.Connection



Setconn=CurrentProject.Connection



DimssqlAsString



ssql="InsertIntotblModeTestValues('test')"



conn.Executessql



conn.Close



Setconn=Nothing



'ifgotthisfarthendatabaseisnotinreadonlymo



'telluser,thenquit



MsgBox"Databasemustbeopenedthroughdesktopshort



DoCmd.Quit



ExitFunction



err_end:



'alliswell,anerrorwasexpected



EndFunction



Thereisatwisttothis:thedatabaseissupposedtobeinreadonlymode,sotheoptimaloutcomeisthattheoperationwillfail

insteadofsucceed.Anerrortrapisimplementedintheroutine,

soiftheerroristriggered,alliswell,andnoactionistaken.If

theinsertsucceeds,thewarningisdisplayed,andtheQuit

methodclosesthedatabase.Thisroutineshouldbecalledby

theAutoExecmacrosothatitrunsimmediatelywhenthe

databaseopens.



Hack9.WorkwithAnyAmountofData



Planamultiple-databasearchitecturetohouseany

amountofdatagigabytes,eventerabytes!

TheonlysizelimitinAccessisthatatablecan'tcontainmore

than1GBofdata.Well,ifthat'sit,thereisalotofopportunity

here.Accessisn'tcutoutforincrediblylargestoresofdata,

granted,butthat'snotthepoint.IfSQLServerorOracleisn't

goingtobeinstalledatyourplaceofbusinessforanotheryear,

takeadvantageofAccess'sflexiblearchitecturetoworkwith

anyamountofdata.

Thetechniqueissimplytomakeaplanforhowtostructurethe

dataamongmultipledatabasefilesandtables.Thereisnorule

thatsaysanAccessapplicationmustresidecompletelyina

singleAccessfile.AnAccessapplicationcanbesplitintoafront

endandabackend.Thatis,theforms,reports,andqueries

stayinthefrontend,andthedataitselfisputintoaseparate

file.Thedatatablesarethenlinkedtothefrontend.Thisis

standardfare,thequintessentialclient/serverinitssimplest

execution,shownhereinFigure1-19.



Figure1-19.Asimplefront-end/back-end

configuration



1.10.1.SplittingUpData

Thereisnoreasontobelimitedtoasinglefileonthebackend.

Theorganizationofandfactsaboutthedatawilldrivethe

decisionsconcerninghowitcanbeparsedintosmallerdata

stores.Forexample,ifyouareworkingwithalargecustomer

base,youcansplitthedatafromonedatatableinto26

tablesoneforeachletterofthealphabet.Figure1-20shows

suchaconfiguration.



Figure1-20.Usingmultipledatabasesontheback

end



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 7. Rid Your Database of Clutter

Tải bản đầy đủ ngay(0 tr)

×