Вградена база данни

Въведение във вградената база данни

Във вградените системи работата на базата данни има характеристиката на времевия лимит. Тук системата от бази данни, приложена към вградената система, се нарича вградена система от бази данни или Вградена система от бази данни в реално време (ERTDBS).

Thereliabilityrequirementsareunquestionable.Theembeddedsystemmustbeabletorununinterruptedlyforalongtimewithoutmanualintervention.Atthesametime,databaseoperationsarerequiredtobepredictable,andthesizeandperformanceofthesystemmustalsobepredictable,soastoensuretheperformanceofthesystem.Embeddedsystemswillinevitablydealwiththeunderlyinghardware,soindatamanagement,theremustalsobetheabilitytocontroltheunderlying,suchaswhendiskoperationswilloccur,thenumberofdiskoperations,howtocontrol,etc.Theabilityoflow-levelcontrolisthekeytodeterminingdatabasemanagementoperations.

Oneofthecurrentchallengesinthedevelopmentofembeddedsoftwaresystemsisembodiedinwhetherasetofreliable,efficientandstablemanagementmodelscanbeestablishedforthemanagementofvariousdata.Embeddeddatabasescanbesaidtohaveemergedasthetimesrequire.

Embeddeddatabaseisanimportantpartofembeddedsystem,andithasalsobecomeanindispensableeffectivemeansformoreandmorepersonalizedapplicationdevelopmentandmanagement.

Embeddeddatabaseshaveawiderangeofuses,suchasconsumerelectronics,mobilecomputingdevices,enterprisereal-timemanagementapplications,networkstorageandmanagement,andvariousspecialequipment.Thismarketiscurrentlyundergoingrapidgrowth.Togiveasimpleexample,mobilephoneswereoriginallyonlyusedformakingcallsandsendingtextmessages.Nowmobilephoneshaveaddedmanynewfunctions,suchasMMS,music,photography,video,etc.,withmoreapplicationfunctions,thesystembecomesmorecomplicated.

Comparisonofcommonlyusedembeddeddatabases

Progress

ProgresssoftwarecompanyannouncedinBeijingat18:00onApril18,2000,thefullreleaseontheLinuxoperatingsystemTherunningdatabaseanditsdeploymentproducts.Progresshastheworld'snumberonemarketshareintheembeddeddatabasemarket.Morethan2millionpeopleintheworldareusingProgressSoftware'sapplicationsoftware.Currently,thenumberofsitesdeployingProgressproductshasexceeded100,000.ThroughProgressSoftware'sfirstLinuxversionoftheembeddeddatabase,independentsoftwaredevelopersandenduserscanportmorethan5,000commercialapplicationsonthispopularoperatingsystem.

----TheproductlaunchedbyProgressSoftwareatthattimewasProgressVersion8.3,andithasnowreachedversion10.2c.Thisisacompletesetofintegrateddevelopmenttools,applicationserversandrelationaldatabaseproducts,andprovidesscalablemulti-layerLinuxsupport.Progresssoftwarecompany’sLinux-specificproductsinclude:

Progress(r)AppServer(tm):Този сървър за приложенияProgress(r)EnterpriseRDBMS(tm),който може да внедри споделени компоненти на приложение в хетерогенна среда:Осигурява решение за мащабируемо съхранение за най-взискателните приложения,които трябва да поддържат големи бази данни,мултипроцесорен хардуер и хиляди едновременни потребители.

----Продуктът за внедряване ProgressVersion8.3 за RedHat6.0Linuxi вече е напълно наличен. Progress пусна продукти за внедряване ProgressVersion9, Progress(r)WebSpeed(r)Version3, Progress(r)Apptivity(tm) и Progress(r)SonicMQ(tm) за Linux.

----QAD, световният ERP доставчик на автомобилната индустрия, поддържа най-новата PROGRESS версия.

SQLite

Основните характеристики на леката база данни SQLite:

1.Събития за поддръжка, без конфигурация, без инсталиране и без администратор;

2.SupportmostSQL92;

3.Acompletedatabaseisstoredinafileonthedisk,thesamedatabasefilecanbeusedondifferentmachines,andthemaximumsupportdatabaseis2T,CharacterandBLOBsupportisonlylimitedtoavailablememory;

4.Цялата система е по-малко от 30 000 реда код, по-малко от 250KB отпечатък на паметта (gcc), повечето приложения са повече от текущия общ клиент/Базата данни от страна на сървъра е бърза и няма други зависимости.

5. Изходният код е отворен, 95% от кода има добри бележки и прост и лесен за използване API. Официалната версия идва с TCL.

Empress (търговска база данни)

Характеристики на етапа на развитие:

1.Programscanbeembedded,thisfeatureenablesapplicationsanddatabasestoworkinaunifiedaddressspace,enhancingImprovethestabilityofthesystemandimprovetheefficiencyofthesystem.

2.Determinetheresponsetime.Empresscanmaketheresponsetimeofthedatarelativelyconsistent.Theusercansetatimeoutlimit.Iftheinsertionormodificationisnotcompletedwithinthespecifiedtime,thesystemwillreportanerror.

3.FastoperationEmpressprovidesakernel-levelCAPI,calledMR,andapplicationswrittenwithMRdonotneedtobeparsedduringexecution.Inaddition,theaccelerationmechanisminMRalsoincludesexcellentlockcontrol,memorymanagementandselectionfunctionsbasedonthenumberofrecords.

4.Flexibledevelopmentmethods,Empressprovidesmultipledevelopmentinterfacestospeedupthedevelopmentprocesswithoutrequiringdeveloperstorelearnthedevelopmentlanguageandfamiliarizethemselveswiththedevelopmentenvironment.

5.Friendlystoragemethod,Empressdatabasecanbeplacedinanystoragedevicesupportedbytheoperatingsystem,andEmpressformscanevenbesplitandplacedindifferentstoragedevices,suchasmemory,harddiskandCD-ROM.

6.Themicro-kernelstructureEmpressishighlyunitized,andtherequiredunitcanbeselectedaccordingtotheneeds,therebyreducingtheresourcesoccupiedbytheEmpressdatabaseintheproduct.

7.Broadplatformsupport,Empresssupportsavarietyofhardwareplatformsandsoftwareplatforms,andcanalsobeportedtothehardwareplatformoroperatingsystemrequiredbythecustomer.

Технически предимства:

1.Микро-ядрена структура, заемаща малко пространство в паметта, особено подходяща за компактен дизайн

2.Работете непрекъснато 24 часа в денонощието, 7 дни в седмицата, без никакви допълнителни операции и без поддръжка

3. CAPI интерфейс на ниво ядро ​​за максимално увеличаване на скоростта на работа

4.Високогъвкав SQLинтерфейс

5. Отлична способност за възстановяване при прекъсване на захранването

6. Силен механизъм за транзакция и заключване

7.Поддръжка на SCSI,RAID,IDE,RAM,CD-RW,DVD-ROM,CF и други носители за съхранение

8.Поддръжка на Unicodecode

9.Двигателят може да бъде зареден на диск и памет

eXtremeDB

Характеристики на XtremeDB:

1.In-memorydatabase,eXtremeDBsavesdatainthemainmemoryinaformatdirectlyusedbytheprogram,whichnotonlyeliminatestheoverheadoffileI/O,butalsoeliminatesthefilesystemThebufferandCachemechanismrequiredbythedatabase.Theresultisalimitspeedofonemicrosecondorlesspertransaction,whichishundredsorthousandsoftimesfasterthanadisk-likedatabase.Asanin-memorydatabase,eXtremeDBnotonlyhashighperformance,butalsohashighdatastorageefficiency.Inordertoimproveperformanceandfacilitatetheuseofprograms,dataisnotcompressedineXtremeDB,and100Mofspacecansaveupto70Mofeffectivedata,whichisunimaginableinotherdatabases.

2.Hybriddatabase,eXtremeDBcannotonlybuildanin-memorydatabasethatrunscompletelyinthemainmemory,butalsoadisk/memoryhybriddatabase.IneXtremeDB,wecallthisoperatingmodebasedondisk,memoryordisk+memoryeXtremeDBFusion.eXtremeDBFusiontakesintoaccountthereal-timeandsecurityrequirementsofdatamanagement,andisastep-by-stepimprovementinreal-timedatamanagement.

3.Embeddeddatabase,theeXtremeDBkernelisincludedintheapplicationintheformofalinklibrary,anditsoverheadisonly50KB~130KB.Whetherinanembeddedsystemorareal-timesystem,eXtremeDBisnaturallyembeddedintheapplicationandworkswithouttheenduser'sknowledge.ThisnaturalembeddednessofeXtremeDBisessentialforreal-timedatamanagement:eachprocessdirectlyaccessestheeXtremeDBdatabase,avoidinginter-processcommunication,therebyeliminatingtheoverheadanduncertaintyofinter-processcommunication.Atthesametime,eXtremeDB'suniquedataformatisconvenientfortheprogramtousedirectly,eliminatingtheoverheadofdatacopyinganddatatranslation,andshorteningthecodeexecutionpathoftheapplication.

4.Theapplication-customizedAPI,theapplication'soperatinginterfacetotheeXtremeDBdatabaseisautomaticallygeneratedaccordingtotheapplicationdatabasedesign,whichnotonlyimprovestheperformance,butalsoeliminatesthedynamicmemoryallocationnecessaryforthegeneralinterface,Therebyimprovingthereliabilityoftheapplicationsystem.Thecustomizationprocessissimpleandconvenient.Theapplicationfeaturessuchastables,fields,datatypes,eventtriggers,andaccessmethodsintheeXtremeDBdatabasearecustomizedbyahigh-levellanguage,andtheC/C++APIinterfaceforaccessingthedatabaseisautomaticallygeneratedthroughtheeXtremeDBpre-compiler.

5. Предсказуемо управление на данни

TheuniquearchitectureofeXtremeDBensuresthepredictabilityofdatamanagement.eXtremeDBisnotonlyfaster,smaller,andmorecertain.Onaserverwith80dual-coreCPUs,eXtremeDBsaves15Brecordsin1TBofmemory;nomatterhowmanyrecordsare,eXtremeDBcanretrievearecordinone-eightymicroseconds.

Firebirdembeddedserverversion

Firebirdembeddedserverversion(EmbeddedServer),FirebirdderivedfromInterbaseopensource,isfullofvitality.AlthoughitssizeisdozensoftimessmallerthanitspredecessorInterbase,itsfunctionsarenotcastrated.InordertoreflectFirebird'sshortandslickfeatures,thedevelopmentteamaddedanembeddedversionafteraddingasuperserverversion.Thelatestversionis2.0.

TheembeddedversionofFirebirdhasthefollowingfeatures:

1.ThedatabasefileisfullycompatiblewiththeFirebirdnetworkversion.Theonlydifferenceisthattheconnectionmethodisdifferent,whichcanrealizezero-costmigration.

2.Thedatabasefileisonlylimitedbytheoperatingsystem,anditsupportssplittingadatabaseintodifferentfiles,breakingthelimitationofthemaximumfileoftheoperatingsystemandimprovingtheIOthroughput.

3. Поддържа напълно стандарта SQL92 и повечето от стандартните функции на SQL-99.

4.Richdevelopmenttoolsupport,mostofthecomponentsbasedonInterbasecanbedirectlyusedinFirebird.

5.Поддържа всички функции на релационни бази данни като транзакции, съхранени процедури и тригери.

6.Можете да напишете свои собствени функции за разширение (UDF).

IntroductiontomSQL

mSQL(miniSQL)isasingle-userdatabasemanagementsystem,freeforpersonaluseandchargeableforcommercialuse.Becauseofitsshortsize,theapplicationsystemdevelopedbyitisespeciallypopularamongInternetusers.mSQL(miniSQL)isasmallrelationaldatabase,theperformanceisnotverygood,theSQLlanguagesupportisnotcomplete,butitisenoughinsomenetworkdatabaseapplications.BecausemSQLisrelativelysimple,itisslightlyfasterthanMySQLwhenrunningsimpleSQLstatements,whileMySQLhasworkedhardonthreadsandindexestoruncomplexSQLstatementsfasterthanmSQL,PostgreSQL,etc.Thelatestversionis3.7releasedonMay8,2005.ThelogoofMSQLisadeer,asshowninthefigurebelow.Figure1mSQLLOGOlogo

TechnicalcharacteristicsofmSQL:Intermsofsecurity,mSQLsetstheaccessauthorityofeachuseroneachhostthroughACLfiles,andthedefaultisallread/write.mSQLlacksmostofthefeaturesofANSISQL,itonlyimplementsaminimalAPI,withouttransactionsandreferentialintegrity.MSQLiscloselyintegratedwithLite(aC-likescriptinglanguage,releasedwiththedistribution),andyoucangetawebsiteintegrationpackagecalledW3-mSQL,whichisJDBC,ODBC,PerlandPHPAPI.

SQLitedatabaseexperiment

Ресурси за обучение

sqliteChinesewebsite:programmingintroduction,opensourceforum

sqliteofficialwebsite: изтегляне на изходния код, Първи стъпки, C/C++ Справочници, различни други документи, форуми за програмисти и др.

Инсталиране на runSQLite на хоста на Linux

Изтегляния на файл qlite-amalgamation-3.5.9.tar.gz

Качванияqlite-amalgamation-3.5.9.tar.gztomikedirectory

Unzipsqlite-amalgamation-3.5.9.tar.gz

tarzxvfsqlite-amalgamation-3.5.9.tar.gz

Въведете директорията на qlite:

cdsqlite-amalgamation-3.5.9

Конфигурация

./configure

Компилиране

p>

направи

Инсталация

makeinstall

Основно инсталирани са следните файлове:

/usr/local/include/sqlite3.h

/usr/local/include/sqlite3ex.h

/usr/local/lib/libsqlite3*

/usr/local/bin/sqlite3

Theheaderfileisusedtoprovidethelibraryfunctionprototypeprovidedbysqlite.Theseheaderfileswillbeincludedwhenwritingdatabaseapplications;thelibraryfunctionisthedynamiclinklibraryprovidedbysqlite,iftheapplicationusesIfSQLitelibraryfunctionsareadded,theselibrarieswillbedynamicallylinkedduringcompilation;thesqliteapplicationinthebindirectoryisashellprogramthatprovidesausercommandlineinterface,anduserscanexperiencethefunctionsprovidedbysqlite.

3.2.1 Използвайте командния ред на хоста, за да изпитате функциите на sqlite, вижте прикачения файл1

3.2.2 Напишете програмния код на приложението, който използва базата данни, както следва:

#включване

#включване

staticintcallback(void*NotUsed,intargc,char**argv,char**azColName){

inti;

за(i=0;i

printf("%s=%s\n",azColName[i],argv[i]?argv[i]:"NULL");

}

printf("\n");

връщане0;

}

intmain(intargc,char**argv){

sqlite3*db;

char*zErrMsg=0;

intrc;

if(argc!=3){

fprintf(stderr,"Използване:%sDATABASESQL-STATEMENT\n",argv[0]);

изход(1);

}

rc=sqlite3_open(argv[1],&db);

ако(rc){

fprintf(stderr,"Can'topendatabase:%s\n",sqlite3_errmsg(db));

sqlite3_close(db);

изход(1);

}

rc=sqlite3_exec(db,argv[2],обратно извикване,0,&zErrMsg);

if(rc!=SQLITE_OK){

fprintf(stderr,"SQLгрешка:%s\n",zErrMsg);

sqlite3_free(zErrMsg);

}

sqlite3_close(db);

връщане0;

}

(1) Създайте asqlite_test.c файл със съдържанието по-горе. Putsqlite_test.c Файлът е поставен в директорията на mike.

(2) Компилиране на файл qlite_test.c:

gcc-I/usr/local/include-L/usr/local/lib-osqlite_testsqlite_test.c-lsqlite3

p>

Приложението, което генерира sqlite_test.

GccОбяснение на параметрите на командния ред:

-Lреж

Whencompiling,searchThepathofthelibrary.Forexample,youcanuseittomakeacatalogforyourownlibrary,otherwisethecompilerwillonlyfinditinthecatalogofthestandardlibrary.Thisdiristhenameofthedirectory.

-lбиблиотека

Посочете библиотеката, използвана при компилиране

-Iреж

Когато използвате #include"file", gcc/g++ първо ще търси файла със заглавки, който сте направили, в текущата директория. Ако не бъде намерен, ще се върне към директорията на файла със заглавки по подразбиране, за да го намери. Ако използвате-аз съм установил директория, той първо ще търси в директорията, която сте направили, и след това ще търси в обичайния ред.

За #include, gcc/g++ ще търси в директорията, зададена от-I, търси, ако не, тогава търси в директорията на заглавния файл по подразбиране на системата

(3) Тествайте тестовата_програма_sqlite

Тестовата програма приема два параметъра: първият параметър е името на файла на базата данни, вторият параметър е SQL изразът, който трябва да бъде изпълнен. Има четири основни места, свързани с SQLite3API в програмата: sqlite3_open()online27,sqlite3_exec()online33,sqlite3_close()onlines30and38.referer toliture3_free 1]за API интерфейса на SQLite3.

Thefollowingisthecompleteprocessoftestingthetestprogram.Itshouldbenotedthatduetothelongcommand,eachcommandisdividedintomultiplelinesofinput,soitlooksclearer:

[root@Sitsang2root]$./testxyz.db"createtable

>tbl0(namevarchar(10),numbersmallint);"

[root@Sitsang2root]$./testxyz.db"вмъкване

>tbl0values('cyc',1);"

[root@Sitsang2root]$./testxyz.db"вмъкване

>tbl0values('dzy',2);"

[root@Sitsang2root]$./testxyz.db"изберете*

>fromtbl0;"

име=цик

число=1

име=dzy

число=2

Explainthetestcommandusedabove:Thefirstcommandcreatesatbl0tableinthexyz.dbdatabasefile.Thetablecontainstwofields.Thefieldnameisavariable-lengthstring.Thetypeofnumberissmallint;thesecondcommandinsertsarecord('cyc',1)intothetbl0tableofthedatabase;thethirdcommandinsertsarecord('dzy',2)intothetbl0tableofthedatabase;Thefourthcommandistoqueryallthecontentsofthetabletbl0,asexpected,thiscommandprintsexceptforthetwonewlyinsertedrecordsinthedatabase.Itcanbeconcludedthatthesecommandshaveindeedworkedinaccordancewiththeexpectedgoals.

Atthesametime,afterinsertingthedatashownaboveintothedatabase,youcanseethatthesizeofthedatabasefilexyz.dbhaschanged:

[root@Sitsang2root]$ll-hxyz.db

-rw-r--r--1rootroot2.0kJan100:18xyz.db

Thesizeofthedatabasefilexyz.dbatthistimeIs2K.Thetestresultsshowthatthedatabasecanworknormally.

Разработете вградена програма за база данни, базирана на qlite

3.3.1 Мигрирайте SQLite към борда за разработка и изтрийте предишната директория sqlite-amalgamation-3.5.9

Unzipsqlite-amalgamation-3.5.9.tar.gz

tarzxvfsqlite-amalgamation-3.5.9.tar.gz

Влезте в директорията на qlite

cdsqlite-amalgamation-3.5.9

Wecreateadirectorysqlite_installunderthe/home/mikedirectoryastheinstallationdirectoryforlateruse.

mkdir/home/mike/sqlite_install

ConfiguresourcefilestogenerateMakefilesuitableforthedevelopmentboard

exportPATH=/usr/local/arm-linux/bin:$PATH

./configure--host=arm-linux--prefix=/home/mike/sqlite_install

Explanation:HowtoinstalllinuxsoftwareTherearegenerallytwoways:rpmmode;use./configureconfiguration,thenmakeandthenmakeinstallmode;pleaserefertorelatedinformation.Here,the--hostparameterreferstothecompiledsoftwaretoberunonthearm-linuxplatform;--prefixreferstothesoftwareinstallationdirectory.TheresultofConfigurerunningistoproduceacorrespondingMakefilefilethatfollowsthetwoparametersspecifiedafterconfigure.

Компилиране

направи

Инсталиране

makeinstall

Enter/home/sqlite_installtowatch,Youcanfindthattherearethreedirectories,namelyinclude,lib,bin.Theheaderfilesrequiredforwritingsqlitedatabaseapplications,libraryfunctionsrequiredforapplicationcompilationandruntime,andsqlitecommandlineprogramsthatcanberunonthearmlinuxsystemarerespectivelystored.

3.3.2WritingandcompilingapplicationsusingSQLitefunctionlibraryWeusethecross-developmenttoolchaintorecompiletheprogramsqlite_test.cwrittenin3.2.2sothatitcanrunonthedevelopmentboard.

Компилирайте изходната програма:

Confirmthatsqlite_test.cisinthemikedirectoryandenterthemikedirectory

arm-linux-gcc-I./sqlite_install/include/-L./sqlite_install/lib/-osqlite_testsqlite_test.c-lsqlite3

След стартиране генерирайте файла armversionsqlite_test

Проверете файла attributesofthesqlite_test

filesqlite_test

Copythesqlite_testfiletoadirectoryoftherootfilesystem,andcopyallthefilesinthe/home/mike/sqlite_install/libdirectorytotherootofthelibraryfunctionsneededforsqlite_testtorunUnderthelibdirectoryofthefiledirectory,recreatetherootfilesystemimageincramfsoryaffsformatandburnittotheexperimentalsystem.

След като системата бъде стартирана, можете да тествате sqlite_testin по същия начин като в 3.2. Приложение 1sqlite3: Програма за достъп до команден ред за SQLiteбаза данни SQLiteбиблиотеката включва обикновена помощна програма от командния ред, нареченаsqlite3която позволява на потребителя да въвежда ръчно и как да изпълнява SQLкоманди отново при използване на стандартна база данни на SQLiteintroduction.Този документ. b>sqlite3.

Първи стъпки

За да стартирате програматаsqlite3просто напишете "sqlite3", последвано от името на файла, който съдържа базата данни SQLite. Ако файлът не съществува, нов се създава автоматично. Програматаsqlite3след това ще подкани да въведетеSQL. Въведете SQL изрази (прекратени с точка и запетая), натиснете "win" и ще бъде изпълнен

Например, за да създадете нова SQLiteбаза данни с име "ex1" с единична таблица с име "tbl1", можете да направите следното:

$sqlite3ex1

SQLiteversion3.3.10

Въведете".help"за инструкции

sqlite>createtabletbl1(onevarchar(10),twosmallint);

sqlite>insertintotbl1values('здравей!',10);

sqlite>insertintotbl1values('сбогом',20);

sqlite>select*fromtbl1;

здравейте!|10

довиждане|20

sqlite>

Можете да прекратите програмата sqlite3, като въведете символа за край на файла на вашата система (обикновено Control-D) или знака за прекъсване (обикновено Control-C).

MakesureyoutypeasemicolonattheendofeachSQLcommand!Thesqlite3programlooksforasemicolontoknowwhenyourSQLcommandiscomplete.Ifyouomitthesemicolon,sqlite3willgiveyouacontinuationpromptandwaitforyoutoentermoretexttobeaddedtothecurrentSQLcommand.ThisfeatureallowsyoutoenterSQLcommandsthatspanmultiplelines.Forexample:

sqlite>CREATETABLEtbl2(

...>f1varchar(30)основен ключ,

...>f2текст,

...>f3real

...>);

sqlite>

Настрана: Запитване до таблицата SQLITE_MASTER

ThedatabaseschemainanSQLitedatabaseisstoredinaspecialtablenamed"sqlite_master".Youcanexecute"SELECT"statementsagainstthespecialsqlite_mastertablejustlikeanyothertableinanSQLitedatabase.Forexample:

$sqlite3ex1

SQlitevversion3.3.10

Въведете".help"за инструкции

sqlite>select*fromsqlite_master;

тип=таблица

име=tbl1

tbl_name=tbl1

rootpage=3

sql=createtabletbl1(onevarchar(10),twosmallint)

sqlite>

ButyoucannotexecuteDROPTABLE,UPDATE,INSERTorDELETEagainstthesqlite_mastertable.Thesqlite_mastertableisupdatedautomaticallyasyoucreateordroptablesandindicesfromthedatabase.Youcannotmakemanualchangestothesqlite_mastertable.

TheschemaforTEMPORARYtablesisnotstoredinthe"sqlite_master"tablesinceTEMPORARYtablesarenotvisibletoapplicationsotherthantheapplicationthatcreatedthetable.TheschemaforTEMPORARYtablesisstoredinanotherspecialtablenamed"sqlite_temp_master".The"sqlite_temp_master"tableistemporaryitself.

Специална команда за sqlite3

Mostofthetime,sqlite3justreadslinesofinputandpassesthemontotheSQLitelibraryforexecution.Butifaninputlinebeginswithadot("."),thenthatlineisinterceptedandinterpretedbythesqlite3programitself.These"dotcommands"aretypicallyusedtochangetheoutputformatofqueries,ortoexecutecertainprepackagedquerystatements.

За изброяване на наличните команди за точки можете да въведете ".help"по всяко време.Например:

sqlite>.help

.bailON|OFFStopafterhittinganerror.DefaultOFF

.databasesListnamesandfilesofattacheddatabases

.dump?TABLE?...DumpthedatabaseinanSQLtextformat

.echoON|OFF Turncommanddechoonoroff

.exit Излезте от тази програма

.explainON|OFF Turnoutput modeподходящ за EXPLAINonoroff.

.header(s)ON|OFFВключете показването на заглавкатаилиизключете

.helpShowthismessage

.importFILETABLEIimportdatafromFILEintoTABLE

.indicesTABLEShownamesofallindicesonTABLE

.loadFILE?ENTRY?Loadanextensionlibrary

.modeMODE?TABLE?SetoutputmodewhereMODEisoneof:

csvСтойности, разделени със запетая

columnLeft-alignedcolumns.(Вижте.width)

htmlHTML

<таблица>код

insertSQLinsertstatementsforTABLE

lineOnevalueperline

listValues​​разделени от.separatorstring

табулатори Стойности, разделени с табулатори

tclTCLlistelements

.nullvalueSTRINGPrintSTRINGinplaceofNULLvalues

.outputFILENAMESendoutputtoFILENAME

.outputstdoutSendoutputtothescreen

.promptMAINCONTINUERзаменетестандартните подкани

.quit Излезте от тази програма

.readFILENAMEExecuteSQLinFILENAME

.schema?TABLE?Покажете изразите CREATE

.separatorSTRINGChangeseparatorusedbyoutputmodeand.import

.show Показване на текущите стойности​​за различни настройки

.tables?PATTERN?ListnamesoftablesmatchingaLIKEpattern

.timeoutMSTryopeninglockedtablesforMSmilliseconds

.widthNUMNUM...Задаване на ширини на колона за режим "колона".

sqlite>

Промяна на изходните формати

Thesqlite3 може да се програмира за показване на резултати от заявка в осем различни формата: "csv", "колона", "html", "вмъкване", "линия", "табулатори" и "tcl". Можете да използвате командата ".mode" dot за превключване между тези изходни формати.

Thedefaultoutputmodeis"list".Inlistmode,eachrecordofaqueryresultiswrittenononelineofoutputandeachcolumnwithinthatrecordisseparatedbyaspecificseparatorstring.Thedefaultseparatorisapipesymbol("|").Listmodeisespeciallyusefulwhenyouaregoingtosendtheoutputofaquerytoanotherprogram(suchasAWK)foradditionalprocessing.

sqlite>.modelist

sqlite>select*fromtbl1;

здравей|10

довиждане|20

sqlite>

Можете да използвате командата".separator"точка, за да промените разделителя за режим на списък. Например, за да промените разделителя на запетая и интервал, бихте могли да направите следното:

sqlite>.separator","

sqlite>select*fromtbl1;

здравей, 10

довиждане, 20

sqlite>

In"line"mode,eachcolumninarowofthedatabaseisshownonalinebyitself.Eachlineconsistsofthecolumnname,anequalsignandthecolumndata.Successiverecordsareseparatedbyablankline.Hereisanexampleoflinemodeoutput:

sqlite>.modeline

sqlite>select*fromtbl1;

one=здравей

две=10

едно=сбогом

две=20

sqlite>

В режим на колона всеки запис не се показва на отделен ред с данните, подравнени в колони. Например:

sqlite>.modecolumn

sqlite>select*fromtbl1;

едно две

-------------------

здравей 10

довиждане20

sqlite>

По подразбиране всяка колона е широка най-малко 10 знака. Данните, които са толкова широки, че са разделени на колона. Можете да регулирате ширината на колоната, като използвате командата "width". Подобно на това:

sqlite>.width126

sqlite>select*fromtbl1;

едно две

------------------

здравей 10

довиждане20

sqlite>

The".width"commandintheexampleabovesetsthewidthofthefirstcolumnto12andthewidthofthesecondcolumnto6.Allothercolumnwidthswereunaltered.Youcangivesasmanyargumentsto".width"asnecessarytospecifythewidthsofasmanycolumnsasareinyourqueryresults.

Ifyouspecifyacolumnawidthof0,thenthecolumnwidthisautomaticallyadjustedtobethemaximumofthreenumbers:10,thewidthoftheheader,andthewidthofthefirstrowofdata.Thismakesthecolumnwidthself-adjusting.Thedefaultwidthsettingforeverycolumnisthisauto-adjusting0value.

Thecolumnlabelsthatappearonthefirsttwolinesofoutputcanbeturnedonandoffusingthe".header"dotcommand.Intheexamplesabove,thecolumnlabelsareon.Toturnthemoffyoucoulddothis:

sqlite>.headeroff

sqlite>select*fromtbl1;

здравей 10

довиждане20

sqlite>

Anotherusefuloutputmodeis"insert".Ininsertmode,theoutputisformattedtolooklikeSQLINSERTstatements.Youcanuseinsertmodetogeneratetextthatcanlaterbeusedtoinputdataintoadifferentdatabase.

Whenspecifyinginsertmode,youhavetogiveanextraargumentwhichisthenameofthetabletobeinsertedinto.Forexample:

sqlite>.modeinsertnew_table

sqlite>select*fromtbl1;

INSERTINTO'new_table'VALUES('hello',10);

INSERTINTO'нова_таблица'VALUES('сбогом',20);

sqlite>

Последният изходен режим е "html". В този режим sqlite3 записва резултатите от заявката в XHTML таблица. Началото

и краят
не са написани, но всички от намесващите сеs,s иса.

Bydefault,sqlite3sendsqueryresultstostandardoutput.Youcanchangethisusingthe".output"command.Justputthenameofanoutputfileasanargumenttothe.outputcommandandallsubsequentqueryresultswillbewrittentothatfile.Use".outputstdout"tobeginwritingtostandardoutputagain.Forexample:

sqlite>.modelist

sqlite>.separator|

sqlite>.outputtest_file_1.txt

sqlite>select*fromtbl1;

sqlite>.изход

$cattest_file_1.txt

здравей|10

довиждане|20

$

Извършване на заявка за схемата на базата данни

Thesqlite3programprovidesseveralconveniencecommandsthatareusefulforlookingattheschemaofthedatabase.Thereisnothingthatthesecommandsdothatcannotbedonebysomeothermeans.Thesecommandsareprovidedpurelyasashortcut.

Например, за да видите списък на таблиците в базата данни, можете да въведете "таблици".

sqlite>.tables

tbl1

tbl2

sqlite>

Командата ".tables" е подобна на режима на списък с настройки след изпълнение на следната заявка:

SELECTnameFROMsqlite_master

WHEREtypeIN('table','view')ANDnameNOTLIKE'sqlite_%'

UNIONALL

SELECTnameFROMsqlite_temp_master

WHEREtypeIN('таблица','изглед')

ПОРЪЧКА1

Всъщност, ако погледнете изходния код на програмата sqlite3 (намерен в дървото на изходния код във файловетеrc/shell.c), ще намерите точно горната заявка.

Командата ".indices" работи по подобен начин за инсталиране на индексите за определена таблица. Командата ".indices" приема единичен аргумент, което е името на таблицата, за която са желани индексите. Последна, но не и последна, е командата ".schema". Ако дадете името на таблицата на ".schema", тя показва оригиналния CREATE израз, използван за създаване на тази таблица и всички подходящи индекси. Имаме:

sqlite>.schema

createtabletbl1(onevarchar(10),twosmallint)

CREATETABLEtbl2(

f1varchar(30)основен ключ,

f2текст,

f3real

)

sqlite>.schematbl2

CREATETABLEtbl2(

f1varchar(30)основен ключ,

f2текст,

f3real

)

sqlite>

Командата".schema" изпълнява същия режим на списък с активи, след което въвежда следната заявка:

SELECTsqlFROM

(ИЗБЕРЕТЕ*FROMsqlite_masterUNIONALL

ИЗБЕРЕТЕ*FROMsqlite_temp_master)

WHEREtype!='meta'

ORDERBYtbl_name,typeDESC,име

Или, ако дадете аргумент на".schema", защото искате схемата само за единична таблица, заявката изглежда така:

SELECTsqlFROM

(ИЗБЕРЕТЕ*FROMsqlite_masterUNIONALL

ИЗБЕРЕТЕ*FROMsqlite_temp_master)

WHEREtype!='meta'ANDsqlNOTNULLANDnameNOTLIKE'sqlite_%'

ORDERBYsubstr(тип,2,1),име

Можете да предоставите аргумент към командата.schema. Ако го направите, заявката изглежда така:

SELECTsqlFROM

(ИЗБЕРЕТЕ*FROMsqlite_masterUNIONALL

ИЗБЕРЕТЕ*FROMsqlite_temp_master)

WHEREtbl_nameLIKE'%s'

ANDtype!='meta'ANDsqlNOTNULLANDnameNOTLIKE'sqlite_%'

ORDERBYsubstr(тип,2,1),име

„%s“ в заявката се заменя от вашия аргумент. Това ви позволява да преглеждате схемата за някои подмножества от базата данни.

sqlite>.schema%abc%

Alongthesesamelines,the".table"commandalsoacceptsapatternasitsfirstargument.Ifyougiveanargumenttothe.tablecommand,a"%"isbothappendedandprependedandaLIKEclauseisaddedtothequery.Thisallowsyoutolistonlythosetablesthatmatchaparticularpattern.

The".databases"commandshowsalistofalldatabasesopeninthecurrentconnection.Therewillalwaysbeatleast2.Thefirstoneis"main",theoriginaldatabaseopened.Thesecondis"temp",thedatabaseusedfortemporarytables.TheremaybeadditionaldatabaseslistedfordatabasesattachedusingtheATTACHstatement.Thefirstoutputcolumnisthenamethedatabaseisattachedwith,andthesecondcolumnisthefilenameoftheexternalfile.

sqlite>.бази данни

Преобразуване на цяла база данни в текстов файл ASCIIT

Използвайте командата ".dump", за да преобразувате цялото съдържание на базата данни в един ASCII текстов файл. Този файл може да бъде преобразуван обратно в база данни, като го изпратите обратно вsqlite3.

Добър начин за създаване на архивно копие на базата данни е следното:

$echo'.dump'|sqlite3ex1|gzip-c>ex1.dump.gz

Това генерира файл с имеex1.dump.gz, който съдържа всичко, от което се нуждаете, за да реконструирате базата данни по-късно или на друга машина. За да реконструирате базата данни, просто въведете:

$zcatex1.dump.gz|sqlite3ex2

ThetextformatispureSQLsoyoucanalsousethe.dumpcommandtoexportanSQLitedatabaseintootherpopularSQLdatabaseengines.Likethis:

$createdbex2

$sqlite3ex1.dump|psqlex2

Други команди за точки

The".explain"dotcommandcanbeusedtosettheoutputmodeto"column"andtosetthecolumnwidthstovaluesthatarereasonableforlookingattheoutputofanEXPLAINcommand.TheEXPLAINcommandisanSQLite-specificSQLextensionthatisusefulfordebugging.IfanyregularSQLisprefacedbyEXPLAIN,thentheSQLcommandisparsedandanalyzedbutisnotexecuted.Instead,thesequenceofvirtualmachineinstructionsthatwouldhavebeenusedtoexecutetheSQLcommandarereturnedlikeaqueryresult.Forexample:

sqlite>.explain

sqlite>explaindeletefromtbl1wheretwo<20;

addropcodep1p2p3

---------------------------------------------------- ----------------

0ListOpen00

1Отворете01tbl1

2Следваща09

3Поле01

4Цяло число200

5Ge02

6Ключ00

7ListWrite00

8Отидете до02

9Noop00

10ListRewind00

11ListRead014

12Изтриване00

13Goto011

14ListClose00

The".timeout"commandsetstheamountoftimethatthesqlite3programwillwaitforlockstoclearonfilesitistryingtoaccessbeforereturninganerror.Thedefaultvalueofthetimeoutiszerosothatanerrorisreturnedimmediatelyifanyneededdatabasetableorindexislocked.

И накрая, ще споменем командата.exit", която кара програмата sqlite3 да излезе.

BerkeleyDB

Технически характеристики:

1.BerkeleyDBisanopensourceembeddeddatabasemanagementsystemthatcanprovideTheprogramprovideshigh-performancedatamanagementservices.Toapplyit,programmersonlyneedtocallsomesimpleAPIstoaccessandmanagedata.(DoesnotuseSQLlanguage)

2.BerkeleyDB предоставя практични API интерфейси за много езици за програмиране, включително C, C++, Java, Perl, Tcl, Python и PHP. Всички операции, свързани с базата данни, се изпълняват еднакво от функционалната библиотека на BerkeleyDB.

3.BerkeleyDBisportableandflexible,andcanrunonalmostallUNIXandLinuxsystemsandtheirvariants,Windowsoperatingsystemsandavarietyofembeddedreal-timeoperatingsystems.BerkeleyDBislinkedtotheapplication,andendusersgenerallydonotfeelthatthereisadatabasesystematall.

4.BerkeleyDBisscalable(Scalable),whichismanifestedinmanyaspects.TheDatabaselibraryitselfisverystreamlined(lessthan300KBoftextspace),butitcanmanagedatabasesupto256TBinsize.Itsupportshighconcurrency,thousandsofuserscanmanipulatethesamedatabaseatthesametime.BerkeleyDBcanrunonembeddedsystemswithstrictconstraintswithasmallenoughspacefootprint.

BerkeleyDBisbetterthanrelationaldatabasesandobject-orienteddatabasesinembeddedapplications.Therearetworeasonsforthis:

(1)BecausethedatabaselibraryisatthesameaddressastheapplicationRuninspace,sodatabaseoperationsdonotrequireinter-processcommunication.Thecostofprocesscommunicationbetweendifferentprocessesonamachineorbetweendifferentmachinesinanetworkismuchgreaterthanthecostoffunctioncalls;(2)becauseBerkeleyDBusesoneforalloperationsGroupAPIinterface,sothereisnoneedtoparseacertainquerylanguage,andthereisnoneedtogenerateanexecutionplan,whichgreatlyimprovestheoperatingefficiency.

DomesticembeddeddatabaseOpenBASELite

OpenBASELiteisanembeddeddatabaseproductdevelopedbyNeusoftGroupCo.,Ltd.Itisatypicallightweightdatabase.Thesizeofthecustomizeddatabaseenginescalesbetween250KBand600KB.Itcansupportmultipledesktopoperatingsystems,mainstreamembeddedsystemplatformsanddifferentprocessors.Asafull-featuredrelationaldatabasesystem,OpenBASELitesupportsstandardSQLsyntax,ACIDtransactionfeatures,backup/restoreandotherfunctions,providesstandardizeddevelopmentinterfacesJDBC,ODBC,andcancontinuetouserelationaldatabaseexperienceinanembeddedenvironment.Forapplicationdevelopment.OpenBASELiteprovidesamemorydatabaseoperatingmode,providinghigh-speeddataaccessandupdatecapabilities.

Характеристики на продукта

1.Completedatamanagementfunctions

OpenBASELiteembeddeddatabasehascompletedatamanagementfunctions,providingasubsetoftheSQL92standardSupport;providesupportforstandarddatatypesandBLOB/CLOBtypes;supportdatabaseintegritycontrol;havecompletedatamanagementcapabilitiesthatcanhandleGB-leveldata;andprovidespatialdatamanagementcapabilities.

2.Гъвкавост на широка платформа

Вградената база данни на OpenBASELite може да работи на Windows2000/2003/XP/Vista/Win7,WindowsMobile5&6,WindowsCE,Linux,EmbeddedLinux,VxWorks,Symbian,Androidи други платформи на операционни системи.

3.Tinycorekernel

Вградената база данни на OpenBASELite има микрофункция на ядрото, която може да бъде персонализирана и адаптирана според нуждите, а размерът на ядрото е мащабируем между 250KB и 600KB.

4.Истинско нулево управление

Не е необходимо да се конфигурират данните въз основа на използването на вградената база данни на OpenBASELite, а „нулевото управление“ е внедрено в приложенията на мобилния терминал.

5.Excellentprocessingperformance

OpenBASELiteembeddeddatabasecanbeusedasamemorydatabasetoachievehigh-speeddataaccessandupdate,andtheprocessingtimeofasingledatadoesnotexceed15us;Intermsofconcurrentprocessingperformance,itprovidesconcurrentaccesscontroloflibrary-levellocksandtable-levellocks,whichimprovestheprocessingperformanceofconcurrentaccesstothedatabasebyprocessesandmultiplethreads.

6.Sufficientsecurityguarantee

OpenBASELiteembeddeddatabasesupportsuseridentityauthenticationandautonomousaccesscontrolofdatabaseobjects,whichcaneffectivelypreventillegalaccesstouserdata;support128-bitAESstorageencryptiontoensurethesecurityofdatabasefiles.

7.Fastfailurerecovery

ProvideslogandfailurerecoverymechanismstoeffectivelyguaranteetheACIDcharacteristicsofthetransaction.Inaddition,italsoprovidesonlinehotbackupandmaster-slavereplicationofthedatabase.,Sothatuserscansimplyandquicklyimprovethereliabilityoftheapplicationsystem.

8.Стандартен интерфейс за достъп

Вградената база данни на OpenBASELite предоставя CAPI интерфейс и JDBC/ODBC стандартен интерфейс за достъп за разработката на вградени приложения.

9.Богати практически инструменти

OpenBASELite предоставя изобилие от практични инструменти за управление на база данни, включително инструменти за графично управление на база данни, инструменти за изграждане на база данни, инструменти за заявки, инструменти за архивиране и възстановяване, инструменти за импортиране на експорт и инструменти за криптиране и декриптиране на база данни и др.

Introductiontoembeddeddatabasesthatcanbeusedformobiledevelopment

Embeddeddatabasesarelightweight,independentlibraries,noservercomponents,nomanagement,asmallcodesize,andLimitedresourcerequirements.Therearecurrentlyseveralembeddeddatabasesthatyoucanuseinmobileapplications.Let'stakealookatthesemostpopulardatabases.

База данни

Съхранение на типове данни

Лиценз

Платформа за поддръжка

BerkeleyDB

релационни,обекти,двойки ключ-стойност,документи

AGPL3.0

Android,iOS

CouchbaseLite

документи

Apache 2.0

Android,iOS

LevelDB

двойки ключ-стойност

Нова BSD

Android,iOS

SQLite

релационен

Обществен домейн

Android,iOS,WindowsPhone,Blackberry

UnQLite

двойки ключ-стойност, документи

BSD2-клауза

Android,iOS,WindowsPhone

Related Articles
TOP