TheDefinitiveGuidetoMySQL,Second
Edition
ISBN:1590591445
byMichaelKofler
Apress©2004(824pages)
Providesathoroughintroductiontothe
installation,configuration,implementation,
andadministrationofMySQL.
TableofContents
TheDefinitiveGuidetoMySQL,SecondEdition
Preface
PartI-Introduction
Chapter1
Chapter2
Chapter3
- WhatIsMySQL?
- TheTestEnvironment
- IntroductoryExample(AnOpinionPoll)
PartII-Fundamentals
Chapter4
Chapter5
Chapter6
Chapter7
Chapter8
Chapter9
Chapter10
- UserInterfaces
- DatabaseDesign
- AnIntroductiontoSQL
- SQLRecipes
- InnoDBTablesandTransactions
- Security
- AdministrationandServerConfiguration
PartIII-Programming
PHP—FundamentalsandProgramming
Techniques
Chapter12 - PHP—LibraryManagement
Chapter13 - PHP—DiscussionForum
Chapter11 -
Chapter14
Chapter15
Chapter16
Chapter17
- Perl
- Java,JSP,JDBC
- CandC++
- VisualBasic,C#,ODBC
PartIV-Reference
Chapter18 - SQLReference
Chapter19 - MySQLTools
Chapter20 - APIReference
PartV-Appendices
AppendixA - Glossary
AppendixB - MySQL4.1
AppendixC - ExampleFiles
AppendixD - Bibliography
Index
ListofFigures
ListofTables
BackCover
TheDefinitiveGuidetoMySQL,SecondEdition,isthe
perfectall-in-oneguidetoMySQL.Whetheryou’renew
toWebapplicationdevelopmentoryou’realreadyan
experienceddatabaseanalyst,thisbookdescribesall
ofthefacetsofMySQLconfiguration,administration,
anddatabaseapplicationdevelopment.Greatly
expandedfromitswidely-praisedfirstedition,this
updatedrevisionprovidesadditionalinformationabout
MySQLtoolssuchasMySQLControlCenterand
phpMyAdmin,databaseAPIsfromseveralpopular
programminglanguagesavailablewithLinuxand
WindowsandthelatestfeaturesfoundinMySQL4.1.
AbouttheAuthor
MichaelKoflerearnedhisPH.D.incomputerscienceat
GrazTechnicalUniversity.Hehaswrittenanumberof
successfulcomputerbooksontopicssuchasVisual
Basic,Linux,Mathematica,andMaple.Koflerisalso
theauthorofDefinitiveGuidetoExcelVBA,Second
Edition,publishedbyApress.
TheDefinitiveGuidetoMySQL,SecondEdition
MichaelKofler
TranslatedbyDavidKramer
TheDefinitiveGuidetoMySQL,SecondEditionCopyright©2004by
MichaelKofler
Allrightsreserved.Nopartofthisworkmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
system,withoutthepriorwrittenpermissionofthecopyrightownerand
thepublisher.
ISBN(pbk):1-59059-144-5
Trademarkednamesmayappearinthisbook.Ratherthanusea
trademarksymbolwitheveryoccurrenceofatrademarkedname,weuse
thenamesonlyinaneditorialfashionandtothebenefitofthetrademark
owner,withnointentionofinfringementofthetrademark.
Translator,Editor,andCompositor:
DavidKramer
EditorialBoard:
DanAppleman
CraigBerry
GaryCornell
TonyDavis
StevenRycroft
JulianSkinner
MartinStreicher
JimSumser
KarenWatterson
GavinWray
JohnZukowski
AssistantPublisher:
GraceWong
ProductionManager:
KariBrooks
Proofreader:
ElizabethBerry
CoverDesigner:
KurtKrames
ManufacturingManager:
TomDebolski
DistributedtothebooktradeintheUnitedStatesbySpringer-VerlagNew
York,Inc.,175FifthAvenue,NewYork,NY,10010andoutsidetheUnited
StatesbySpringer-VerlagGmbH&Co.KG,Tiergartenstr.17,69112
Heidelberg,Germany
IntheUnitedStates:phone1-800-SPRINGER,email
,orvisit.OutsidetheUnitedStates:fax+496221345229,email
,orvisit.
Forinformationontranslations,pleasecontactApressdirectlyat2560
NinthStreet,Suite219,Berkeley,CA94710.Phone510-549-5930,fax
510-549-5939,email,orvisit
.
Theinformationinthisbookisdistributedonan"asis"basis,without
warranty.Althougheveryprecautionhasbeentakeninthepreparationof
thiswork,neithertheauthornorApressshallhaveanyliabilitytoany
personorentitywithrespecttoanylossordamagecausedorallegedto
becauseddirectlyorindirectlybytheinformationcontainedinthiswork.
Thesourcecodeforthisbookisavailabletoreadersat
,intheDownloadssection.Youwillneedto
answerquestionspertainingtothisbookinordertosuccessfully
downloadthecode.
AbouttheAuthor
MICHAELKOFLEREARNEDHISPH.D.incomputerscienceatGraz
TechnicalUniversity.Hehaswrittenanumberofsuccessfulcomputer
booksontopicssuchasVisualBasic,Linux,Mathematica,andMaple.
KoflerisalsotheauthorofDefinitiveGuidetoExcelVBA,Second
Edition,publishedbyApress.
AbouttheTranslator
DAVIDKRAMEREARNEDHISPH.D.inmathematicsattheUniversityof
Maryland,andhisM.A.inmusicatSmithCollege.Formanyyearshe
workedinacademia,firstasaprofessorofmathematicsandcomputer
science,andlaterasadirectorofacademiccomputing.Overthepast
eightyearshehaseditedhundredsofbooksinmathematicsandthe
sciences,andhastranslatedanumberofbooksinavarietyoffields,
includingDefinitiveGuidetoExcelVBA,byMichaelKofler;Enterprise
JavaBeans2.1,byStefanDenningerandIngoPeters;andCryptography
inCandC++,byMichaelWelschenbach,allpublishedbyApress.Other
translationsincludeTheGame'sAfoot!GameTheoryinMythand
Paradox,byAlexanderMehlmann;thechildren'smusicalRedRiding!
RedRiding!,byErnstEkkerwithmusicbySergeiDreznin;InQuestof
Tomorrow'sMedicines,byJürgenDrews;andthenovelToErrIsDivine,
byÁgotaBozai,whichwillbepublishedbyCounterpointPressinApril
2004.
Preface
MYSQLISTHEMOSTWIDELYuseddatabasesystemintheOpen
Sourcesector.Therearemanyreasonswhythisisso:
MySQLisfast.
MySQLisstable.
MySQLiseasytolearn.
MySQLrunsonpopularoperatingsystems(Windows,Linux,Mac
OSX,variousflavorsofUnix).
MySQLapplicationscanbecreatedinagreatvarietyof
programminglanguages(suchasC,C++,C#,Java,Perl,PHP,
Python,VB,andVB.NET).
MySQLisextensivelydocumentedontheInternet,andthereare
manybooksonthesubjectavailable.
MySQLisavailableformanyapplicationsfreeofcharge(GPL
license).
SincethelicensingrestrictionsofGPLareunacceptableformany
commercialapplications,therearereasonablypricedcommercial
licensesandoptionalsupportcontracts.
MySQLisonthevergeofrepeatinginthedatabasemarketthe
successachievedbyLinuxintheoperatingsystemsector.In
combinationwithPHPorPerl,MySQLisprovidingthedatabase
systemformoreandmorewebsites.(Afavoritecombinationis
Linux+Apache+MySQL+PerlorPHP.Suchsystemsarecalled
"LAMPsystems"forshort.)MySQLisnotjustforsmallwebsites;
itisusedbylargefirmswithhugeamountsofdata,suchas
Yahoo!,Slashdot,andGoogle.
WhatDoesThisBookOffer?
Thisbookprovidesacompleteapplication-andexample-oriented
introductiontothedatabasesystemMySQL.Nopreviousknowledge,
eitherofSQLordatabasedesign,isassumed.
TheintroductoryPartIofthebookbeginswithanextensiveintroduction
oninstallationunderWindowsandLinux.Wealsoconsiderthe
installationofcomponentsthatareusedincombinationwithMySQL
(Apache,PHP,phpMyAdmin,Perl,Connector/MyODBC).Buildingon
this,ourfirstexamplewillshowthebasicuseofMySQLandPHP.
PartII,"Fundamentals,"providesalargeamountofbackgroundmaterial
ontheuseofvarioususerinterfaces,onthedatabaselanguageSQL,on
theproperdesignofdatabases,ontheuseofInnoDBtables,onthe
accesssystemofMySQL,andonmanyothertopicsonadministration
(suchasbackups,logging,andreplication).
InPartIII,"Programming,"weemphasizethelanguagePHP:Three
chapterscoverbasictechniquesofprogrammingandshowhowto
constructtwoextensiveexamples(bookkeeping,adiscussionforum).
MostofthePHPexamplescanbetriedoutliveonmywebsite.Wedeal
withotherprogramminglanguages,too,withchaptersdevotedtoPerl,
Java,C/C++,andVB/VB.NET/C#.
Weendthemaintextwithareferencesection(PartIV)thatprovidesan
overviewoftheSQLcommandsofMySQL,thecommandsandoptions
oftheadministrativetools,andthefunctionsofimportantprogramming
interfaces(PHP,Perl,C,Java).
Finally,thereareseveralappendices,comprising(A)aglossaryofterms,
(B)breakingnewsontheforthcomingMySQLversion4.1,(C)information
ontheexamplefilesforthisbook(availableatwww.apress.com),and
(D)abibliographywithsuggestionsforfurtherreading.
Incombinationwiththeexampledatabasesandprograms,thisbook
shouldprovideagoodfoundationforthedevelopmentofyourown
databaseapplications.InthisIwishyoumuchfunandsuccess.
MichaelKofler,August2003
<>
/>
WhatIsNewintheSecondEdition?
Thereismuchthatisnew.Thisbookhasbeencompletelyrevised,from
thefirstpagetothelast.(Ittookaslongtoproducethissecondeditionas
towritethefirsteditionfromscratch!)Thefollowinglistindicatesthemost
importantchanges:
MySQL:ThebooknowcoversMySQL4.0andtosomeextent
MySQL4.1.Thesechangesappearthroughouttheentirebook,
frominstallationtothereferencesectiontotheappendixes.
Userinterface:Thisbookdescribesthenewuserinterface
MySQLControlCenterandthelatestversionofphpMyAdmin.
SQLrecipes:ThereisanewchapterintheintroductiononSQL
thatprovidesanswerstofrequentlyaskedSQLquestions:How
canIprocessthefirst/lastndatarecords?Howcanduplicate
recordsbelocated?HowaresubSELECTcommandsformedin
MySQL4.0and4.1?Howcanafull-textsearchbeaccomplished
efficiently?
InnoDBtables,transactions,rulesforintegrity:Anewchapter
isdevotedtotheInnoDBtableformat.InnoDBtablesenablethe
executionoftransactionswithrowlevellockingandtheprotection
oftheintegrityofrelationsbetweentables(foreignkey
constraints).
Security,accessrights:Chapter9dealswithalltheinnovations
dealingwithaccessrights(MySQLprivileges).Anewsection
givesanumberofpracticaltipsonsolvingproblemswith
establishingconnections.
Administration:Everythingrelatedtoadministrationiscontained
inasingleclearlystructuredchapter.Newsectionsdealwiththe
administrationofInnoDBtablesandservertuning(including
QueryCache).
PHP:AllPHPexampleshavebeenreworkedinPHP4.3.The
HTMLcodegeneratedfromthePHPexamplesisnowlargely
XHMTLcompatible.ThePHPtexthasbeendividedoverfour
chaptersandisnowmoreclearlystructured.InChapter11,on
techniquesofPHPprogramming,wenowalsodealwithstoring
images(fileupload/download).
Java:AnewchapterdescribesprogrammingofJavaandJSP
applicationsonthebasisofJDBCandConnector/JDBC.
C/C++:AnewchapterdiscussesthedevelopmentofCandC++
programs.
VB6:AnewexampleprogramdemonstratestheuseofBLOBs.
VB.NET,C#:AnewsectioninChapter17dealswiththe
developmentofADO.NETapplicationswiththeprogramming
languagesVB.NETandC#.
Reference:Thethreereferencechaptershavebeenthoroughly
broughtuptodateandexpandedwithnewsections(Cfunctions,
JDBCclasses).
MySQL4.1:AppendixBbringstogetherallknownchangesin
MySQL4.1:improvedcharactersetsupport(includingUnicode),
theuseofsubSELECTs,themanagementofgeometricand
geographicdata(GIS),theuseofprecompiledcommands
(preparedstatements),etc.
WhatDoesThisBookNotOffer?
SeveralchaptersinthisbookdealwiththeprogrammingofMySQL
applicationsinavarietyofprogramminglanguages,suchasPHP,Perl,
C,C++,Java,andVisualBasic.Thesechaptersassumethatthereader
isfamiliarwiththespecificprogramminglanguage.(Thereissimplyno
roominthisbooktoofferanintroductiontoanumberofprogramming
languages.)Inotherwords,youwillprofitfrom,say,thePHPchapterin
thisbookonlyifyouarealreadyfamiliarwiththeprogramminglanguage
PHP.
ExamplePrograms,SourceCode
Totheextentthatwearedealingwithwebapplications,almostallofthe
applicationsinthisbookcanbetriedoutdirectlyonmywebsite
(www.kofler.cc).Thesourcecodeforalltheexamplesisavailableat
www.apress.cominthedownloadssection.
Inthelongerprogramlistingsinthisbookyouwillfindatthebeginningof
theexampleacommentlinethatspecifiesthefilenameappearinginthe
examplefilesonthewebsite,forexample,
<!--php-programming/simpleinput.php-->
Tosavespace,sometimesonlythemostinterestingpassagesinthe
programcodeareprinted.
Versions
ThefunctionalityofMySQLandoftheprograms,programming
languages,andlibrariesplacedinitsenvironmentchangeswithevery
newversion—whichsometimesappearweekly.Thefollowingoverview
indicateswhichversionsIhaveworkedwith(explanationsofthevarious
nameswillappearatappropriateplacesinthebook):
Apache:Versions1.3.nand2.0.n.
Connector/J:Version3.0.6.
Connector/ODBC(formerlyMyODBC):Version3.51.06.
gcc:Version3.2
Java:Version1.4.1(Windows)and1.3.1(Linux).
JSP:seeTomcat.
Linux:MySQLandotherprogramsweretestedforthisbook
underLinuxandWindows.UnderLinux,thedistributionsRedHat
8.0and9.0(beta3)andSuSE8.1and8.2(beta5)wereused.
MySQL:Version4.0.14.Inmostoftheexampleprograms,
however,compatibilitywithMySQL3.23.nwastakeninto
account,sincethisversionisstillinusebymanyInternetservice
providers.Ontheotherhand,thelatestdevelopmentsofMySQL
4.1weretestedwithadevelopmentversion(alphaversion,from
endofJuly2003),asdescribedinAppendixB.
Connector/C++:Version1.7.9.
Perl:Versions5.6and5.8.
PHP:Versions4.2and4.3.Asfileidentifier,thesuffix*.phpis
generallyused.
phpMyAdmin:Version2.4.
Tomcat:Version4.0.4(JavaServlet2.2,JavaServer1.1).
VisualBasic,VBA,ADO:VisualBasicprogramswere
developedandtestedwithVB6andVBA6andADOversions2.1
and2.7.
VisualBasic.NET,C#,ADO.NET,ASP.NET:Alloftheseare
basedonVisualStudio.NET2002(.NETFramework1.0).
Windows:AlltestsunderWindowswerecarriedoutwith
Windows2000.Inprinciple,everythingshouldbevalidfor
WindowsNT4,WindowsXP,andfutureversionsofWindows.
Notation
SQLcommandsandfunctions,aswellasmethods,classes,andkey
wordsinSQL,C,Java,PHP,Perl,VB,etc.,generallyappearinitalic
(e.g.,SELECT,mysql_query).(Note,however,thatwhenthebackground
textisitalic,asinthegray"Remark,""Tip,""Caution,"and"Pointer"
boxesandsomesectionheadings,suchcommandsandfunctionswill
appearinaromanfont;e.g.,SELECT.)
Unix/Linuxusernamesalsoappearinitalic(e.g.,root,mysql).
MENUCOMMANDSUSECAPSANDSMALLCAPS(e.g.,FILE|
OPEN).
Keyboardshortcutsuseamonospacefont(e.g.,
Shift+Delete).
Fileanddirectorynamesalsousethemonospacefont(e.g.,
/usr/localorC:\Windows).
Programsandprogrammingcommandsareinthemonospace
fontaswell(e.g.,mysqlorcmd.exe).
MySQLoptionsandconfigurationparametersappearinregular
romantype(e.g.,default-charset).
Programlistingsandcommandlineinputappearinasans
seriffont.
SQLcommandsaregenerallywritteninUPPERCASEletters.Thisisnot
asyntacticnecessity,butmerelyaconvention.MySQLdoesnot
distinguishbetweenuppercaseandlowercaseininterpretingSQL
commands.
InspecifyingWindowsdirectories,wewilloftennotwriteouttheabsolute
path,sinceitdependsinanycaseontheparticularinstallation.We
observethefollowingconventions:
\Windows\meanstheWindowsdirectory(e.g.,C:\Windowsor
D:\WinNT4).
Programs\meansthedirectoryunderWindowsforprogram
installation(e.g.,C:\ProgramsorD:\ProgramFiles).
Mysql\meanstheMySQLinstallationdirectory(e.g.,C:\Mysql
orD:\ProgramFiles\Mysql).
Commands
Manycommandswillbepresentedinthisbook.Wewillbemovingback
andforthbetweentheUnix/LinuxandWindowsconventions.The
followingtwocommandsareequivalent:
root#mysqladmin-uroot-hlocalhostpasswordxxx
>mysqladmin-uroot-hlocalhostpasswordxxx
Ineachcasewehavegiventhesystemprompt(root#forUnix/Linux
and>forWindows).Youtypeinonlywhatfollowstheprompt(herein
boldfacetype).UnderUnix/Linuxitispossibletodividelonginputsover
severallines.Thelinesareseparatedbymeansofthebackslashsymbol
\.Weshalloftenusethisconventioninthisbook.Thefollowingcommand
thuscorrespondstothecommandabove:
root#mysqladmin-uroot-hlocalhost\
passwordxxx
Ineachcase,xxxistobereplacedbytherelevanttext(inthisexample
byyourpassword).Wehaveindicatedthatxxxisdummytextbytheuse
ofaslantfont.
Abbreviations
Ihaveattemptedinthisbooktomakeaslittleuseofabbreviationsas
possible.However,thereareseveralabbreviationsthatwillbeused
repeatedlywithoutbeingintroducedanewineachchapter:
ADO
ActiveDataObjects(Microsoftdatabaselibrary)
BLOB
BinaryLargeObject(binarydatablock)
GPL
GNUPublicLicense(importantlicenseforOpenSource
software)
HTML
HyperTextMarkupLanguage(formatfordescribingweb
documents)
InnoDB
Notanabbreviation,butthenameofacompanythathas
developedaspecialtableformatforMySQL(InnoDBtables)
ISP
InternetServiceProvider
JSP
JavaServerPages
MySQL
Thenameofthecompanythatdevelopedthedatabase
systemMySQL
ODBC
OpenDatabaseConnectivity(interfacefordatabaseaccess,
particularlypopularunderWindows)
PHP
PHPHypertextPreprocessor(ascriptingprogramming
languageforHTMLpages)
RPM
RedHatPacketManager(aformatforLinuxsoftware
packages)
SQL
StructuredQueryLanguage(databaseprogramming
language)
URL
UniformResourceLocator(Internetaddressoftheform
/>
VB
VisualBasic(programminglanguage)
VisualBasicforApplications(programminglanguagewithin
VBA
theMicrosoftOfficepackage)
PartI:Introduction
ChapterList
Chapter1:WhatIsMySQL?
Chapter2:TheTestEnvironment
Chapter3:IntroductoryExample(AnOpinionPoll)
Chapter1:WhatIsMySQL?
Overview
Thischapterbeginswithanoverviewofthemostimportantconcepts
fromtheworldofdatabasesandthendelvesintothepossibilitiesand
limitationsofMySQL.WhatisMySQL?Whatcanitdo,andwhatisit
unabletodo?
InadditiontodescribingthecentralfunctionsofMySQL,weshallalso
discussfullytheissueoflicensingMySQL.Whenisonepermittedtouse
MySQLwithoutpayment,andwhenisalicenserequired?
WhatIsaDatabase?
Beforewecananswerthecentralquestionofthischapter,namely,What
isMySQL?youandImustfindacommonlanguage.Therefore,this
sectionpresentsarudimentarydatabaseglossary,withoutgoinginto
greatdetail.(Ifyouhavealreadyhadsignificantdealingswithrelational
databases,youcanskipthenextcoupleofpagesingoodconscience.)
Thereisscarcelytobefoundatermthatislessprecisethandatabase.A
databasecanbealistofaddressesresidinginaspreadsheetprogram
(suchasExcel),oritcanbetheadministrationfilesofa
telecommunicationsfirminwhichseveralmillioncallsareregistered
daily,theirchargesaccuratelycalculated,monthlybillscomputed,and
warningletterssenttothosewhoareinarrears.Asimpledatabasecan
beastand-aloneoperation(residinglocallyonacomputerforasingle
user),whileothersmaybeusedsimultaneouslybythousandsofusers,
withthedataparceledoutamongseveralcomputersanddozensofhard
drives.Thesizeofadatabasecanrangefromafewkilobytesintothe
terabytes.[1]
Inordinaryusage,theword"database"isusedtorefertotheactualdata,
theresultingdatabasefiles,thedatabasesystem(suchasMySQLor
Oracle),oradatabaseclient(suchasaPHPscriptoraprogramwritten
inC++).Thustherearisesagreatpotentialforconfusionassoonastwo
peoplebegintoconverseonthesubjectofdatabases.
Relations,DatabaseSystems,Servers,andClients
Adatabaseisanorderedcollectionofdata,whichisnormallystoredin
oneormoreassociatedfiles.Thedataarestructuredastables,where
crossreferencesamongtablesarepossible.Theexistenceofsuch
relationsamongthetablesleadstothedatabasebeingcalledarelational
database.
Letusclarifymatterswithanexample.Adatabasemightconsistofa
tablewithdataonafirm'scustomers(name,address,etc.),atablewith
dataontheproductsthefirmoffers,andfinally,atablecontainingthe