MySQL Cookbook
By Paul DuBois
Preface
The MySQL dat abase m anagem ent syst em has becom e quit e popular in recent years. This has been t rue especially in t he Linux and open source com m unit ies, but MySQL's presence in t he com m ercial sect or now is increasing as well. I t is well liked for several reasons: MySQL is fast , and it 's easy t o set up, use, and adm inist rat e. MySQL runs under m any variet ies of Unix and Windows, and MySQL-based program s can be writ t en in m any languages. MySQL is especially heavily used in com binat ion wit h a web server for const ruct ing dat abase-backed web sit es t hat involve dynam ic cont ent generat ion.
Wit h MySQL's rise in popularit y com es t he need t o address t he quest ions posed by it s users about how t o solve specific problem s. That is t he purpose of MySQL Cookbook. I t 's designed t o serve as a handy resource t o which you can t urn when you need quick solut ions or t echniques for at t acking part icular t ypes of quest ions t hat com e up when you use MySQL. Nat urally, because it 's a cookbook, it cont ains recipes: st raight forward inst ruct ions you can follow rat her t han develop your own code from scrat ch. I t 's writ t en using a problem - and-solut ion form at designed t o be ext rem ely pract ical and t o m ake t he cont ent s easy t o read and assim ilat e. I t cont ains m any short sect ions, each describing how t o writ e a query, apply a t echnique, or develop a script t o solve a problem of lim it ed and specific scope. This book doesn't at t em pt t o develop full- fledged applicat ions. I nst ead, it 's int ended t o assist you in developing such applicat ions yourself by helping you get past problem s t hat have you st um ped.
For exam ple, a com m on quest ion is, " How can I deal wit h quot es and special charact ers in dat a values when I 'm writ ing queries?" That 's not difficult , but figuring out how t o do it is frust rat ing when you're not sure where t o st art . This book dem onst rat es what t o do; it shows you where t o begin and how t o proceed from t here. This knowledge will serve you repeat edly, because aft er you see what 's involved, you'll be able t o apply t he t echnique t o any kind of dat a, such as t ext , im ages, sound or video clips, news art icles, com pressed files, PDF files, or word processing docum ent s. Anot her com m on quest ion is, " Can I access t ables from t wo dat abases at t he sam e t im e?" The answer is " Yes," and it 's easy t o do because it 's j ust a m at t er of knowing t he proper SQL synt ax. But it 's hard t o do unt il you see how; t his book will show you. Ot her t hings t hat you'll learn from t his book include:
•
How t o use SQL t o select , sort , and sum m arize records.•
How t o find m at ches or m ism at ches bet ween records in t wo t ables.•
How t o perform a t ransact ion.•
How t o det erm ine int ervals bet ween dat es or t im es, including age calculat ions.•
How t o rem ove duplicat e records.•
How t o st ore im ages int o MySQL and ret rieve t hem for display in web pages.•
How t o convert t he legal values of an ENUM colum n int o radio but t ons in a web page,or t he values of a SET colum n int o checkboxes.
•
How t o use pat t ern m at ching t echniques t o cope wit h m ism at ches bet ween t heCCYY-MM-DD
dat e form at t hat MySQL uses and dat es in your dat afiles.•
How t o copy a t able or a dat abase t o anot her server.•
How t o resequence a sequence num ber colum n, and why you really don't want t o.One part of knowing how t o use MySQL is underst anding how t o com m unicat e wit h t he server—t hat is, how t o use SQL, t he language t hrough which queries are form ulat ed.
Therefore, one m aj or em phasis of t his book is on using SQL t o form ulat e queries t hat answer part icular kinds of quest ions. One helpful t ool for learning and using SQL is t he m ysql client program t hat is included in MySQL dist ribut ions. By using t his client int eract ively, you can send SQL st at em ent s t o t he server and see t he result s. This is ext rem ely useful because it provides a direct int erface t o SQL. The m ysql client is so useful, in fact , t hat t he ent ire first chapt er is devot ed t o it .
But t he abilit y t o issue SQL queries alone is not enough. I nform at ion ext ract ed from a dat abase oft en needs t o be processed furt her or present ed in a part icular way t o be useful. What if you have queries wit h com plex int errelat ionships, such as when you need t o use t he result s of one query as t he basis for ot hers? SQL by it self has lit t le facilit y for m aking t hese kinds of choices, which m akes it difficult t o use decision- based logic t o det erm ine which queries t o execut e. Or what if you need t o generat e a specialized report wit h very specific form at t ing requirem ent s? This t oo is difficult t o achieve using j ust SQL. These problem s bring us t o t he ot her m aj or em phasis of t he book—how t o writ e program s t hat int eract wit h t he MySQL server t hrough an applicat ion program m ing int erface ( API ) . When you know how t o use MySQL from wit hin t he cont ext of a program m ing language, you gain t he abilit y t o exploit MySQL's capabilit ies in t he following ways:
•
You can rem em ber t he result from a query and use it at a lat er t im e.•
You can m ake decisions based on success or failure of a query, or on t he cont ent of t he rows t hat are ret urned. Difficult ies in im plem ent ing cont rol flow disappear when using an API because t he host language provides facilit ies for expressing decision-based logic: if- t hen-else const ruct s, while loops, subrout ines, and so fort h.•
You can form at and display query result s however you like. I f you're writ ing acom m and- line script , you can generat e plain t ext . I f it 's a web-based script , you can generat e an HTML t able. I f it 's an applicat ion t hat ext ract s inform at ion for t ransfer t o som e ot her syst em , you m ight writ e a dat afile expressed in XML.
When you com bine SQL wit h a general purpose program m ing language and a MySQL client API , you have an ext rem ely flexible fram ework for issuing queries and processing t heir result s. Program m ing languages increase your expressive capabilit ies by giving you a great deal of addit ional power t o perform com plex dat abase operat ions. This doesn't m ean t his book is com plicat ed, t hough. I t keeps t hings sim ple, showing how t o const ruct sm all building blocks by using t echniques t hat are easy t o underst and and easily m ast ered.
nucleic acids, but t hese basic elem ent s have been com bined t o produce t he ast onishing array of biological life we see all around us. Sim ilarly, t here are only 12 not es in t he scale, but in t he hands of skilled com posers, t hey can be int erwoven t o produce a rich and endless variet y of m usic. I n t he sam e way, when you t ake a set of sim ple recipes, add your im aginat ion, and apply t hem t o t he dat abase program m ing problem s you want t o solve, you can produce t hat are perhaps not works of art , but cert ainly applicat ions t hat are useful and t hat will help you and ot hers be m ore product ive.
MySQL APIs Used in This Book
MySQL program m ing int erfaces exist for m any languages, including ( in alphabet ical order) C, C+ + , Eiffel, Java, Pascal, Perl, PHP, Pyt hon, Ruby, Sm allt alk, and Tcl.[ ] Given t his fact , writ ing a MySQL cookbook present s an aut hor wit h som et hing of a challenge. Clearly t he book should provide recipes for doing m any int erest ing and useful t hings wit h MySQL, but which API or API s should t he book use? Showing an im plem ent at ion of every recipe in every language would result eit her in covering very few recipes or in a very, very large book! I t would also result in a lot of redundancy when im plem ent at ions in different languages bear a st rong resem blance t o each ot her. On t he ot her hand, it 's wort hwhile t aking advant age of m ult iple languages, because one language oft en will be m ore suit able t han anot her for solving a part icular t ype of problem .
[ ] To see what API s are current ly available, visit t he developm ent port al at t he MySQL web sit e, locat ed at ht t p: / / www.m ysql.com / port al/ developm ent / ht m l/.
To resolve t his dilem m a, I 've picked a sm all num ber of API s from am ong t hose t hat are available and used t hem t o writ e t he recipes in t his book. This lim it s it s scope t o a m anageable num ber of API s while allowing som e lat it ude t o choose from am ong t hem . The prim ary API s covered here are:
Per l
Using t he DBI m odule and it s MySQL- specific dr iv er
PHP
Using it s set of built - in MySQL suppor t funct ions
Pyt hon
Using t he DB- API m odule and it s MySQL- specific dr iv er
Java
Using a MySQL- specific dr iver for t he Java Dat abase Connect ivit y ( JDBC) int er face
capabilit ies. I n part icular, it 's very popular for writ ing MySQL program s. PHP also is widely deployed, and it s use is increasing st eadily. One of PHP's st rengt hs is t he ease wit h which you can use it t o access dat abases, m aking it a nat ural choice for MySQL script ing. Pyt hon and Java are not as popular as Perl or PHP for MySQL program m ing, but each has significant num bers of followers. I n t he Java com m unit y in part icular, MySQL seem s t o be m aking st rong inroads am ong developers who use JavaServer Pages ( JSP) t echnology t o build dat abase-backed web applicat ions. ( An anecdot al observat ion: Aft er I wrot e MySQL ( New Riders) , Pyt hon and Java were t he t wo languages not covered in t hat book t hat readers m ost oft en said t hey would have liked t o have seen addressed. So here t hey are! )
I believe t hese languages t aken t oget her reflect pret t y well t he m aj orit y of t he exist ing user base of MySQL program m ers. I f you prefer som e language not shown here, you can st ill use t his book, but be sure t o pay careful at t ent ion t o Chapt er 2, t o fam iliarize yourself wit h t he book's prim ary API languages. Knowing how dat abase operat ions are perform ed wit h t he API s used here will help you underst and t he recipes in lat er chapt ers so t hat you can t ranslat e t hem int o languages not discussed.
Who This Book Is For
This book should be useful for anybody who uses MySQL, ranging from novices who want t o use a dat abase for personal reasons, t o professional dat abase and web developers. The book should also appeal t o people who do not now use MySQL, but would like t o. For exam ple, it should be useful t o beginners who want t o learn about dat abases but realize t hat Oracle isn't t he best choice for t hat .
I f you're relat ively new t o MySQL, you'll probably find lot s of ways t o use it here t hat you hadn't t hought of. I f you're m ore experienced, you'll probably be fam iliar wit h m any of t he problem s addressed here, but you m ay not have had t o solve t hem before and should find t he book a gr eat t im esaver; t ake advant age of t he recipes given in t he book and use t hem in your own program s rat her t han figuring out how t o writ e t he code from scrat ch.
The book also can be useful for people who aren't even using MySQL. You m ight suppose t hat because t his is a MySQL cookbook and not a Post greSQL cookbook or an I nt erBase cookbook t hat it won't apply t o dat abases ot her t han MySQL. To som e ext ent t hat 's t rue, because som e of t he SQL const ruct s are MySQL- specific. On t he ot her hand, m any of t he queries ar e
st andard SQL t hat is port able t o m any ot her dat abase engines, so you should be able t o use t hem wit h lit t le or no m odificat ion. And several of our program m ing language int erfaces provide dat abase- independent access m et hods; you use t hem t he sam e way regardless of which dat abase you're connect ing t o.
The m at erial ranges from int roduct ory t o advanced, so if a recipe describes t echniques t hat seem obvious t o you, skip it . Or if you find t hat you don't underst and a recipe, it m ay be best t o set it aside for a while and com e back t o it lat er, perhaps aft er reading som e of t he
More advanced readers m ay wonder on occasion why in a book on MySQL I som et im es provide explanat ory m at erial on cert ain basic t opics t hat are not direct ly MySQL- relat ed, such as how t o set environm ent variables. I decided t o do t his based on m y experience in helping novice MySQL users. One t hing t hat m akes MySQL at t ract ive is t hat it is easy t o use, which m akes it a popular choice for people wit hout ext ensive background in dat abases. However, m any of t hese sam e people also t end t o be t hwart ed by sim ple barriers t o m ore effect ive use of MySQL, as evidenced by t he com m on quest ion, " How can I avoid having t o t ype t he full pat hnam e of m ysql each t im e I invoke it ?" Experienced readers will recognize im m ediat ely t hat t his is sim ply a m at t er of appropriat ely set t ing t he PATH environm ent variable t o include t he direct ory w here m ysql is inst alled. But ot her readers will not , part icularly Windows users who are used t o dealing only wit h a graphical int erface and, m ore recent ly, Mac OS X users who find t heir fam iliar user int erface now augm ent ed by t he powerful but som et im es m yst erious com m and line provided by t he Term inal applicat ion. I f you are in t his sit uat ion, you'll find t hese m ore elem ent ary sect ions helpful in knocking down barriers t hat keep you from using MySQL m ore easily. I f you're a m ore advanced user, j ust skip over such sect ions.
What's in This Book
I t 's very likely when you use t his book t hat you'll have an applicat ion in m ind you're t rying t o develop but are not sure how t o im plem ent cert ain pieces of it . I n t his case, you'll already know what t ype of problem you want t o solve, so you should search t he t able of cont ent s or t he index looking for a recipe t hat shows how t o do what you want . I deally, t he recipe will be j ust what you had in m ind. Failing t hat , you should be able t o find a recipe for a sim ilar problem t hat you can adapt t o suit t he issue at hand. ( I t ry t o explain t he principles involved in developing each t echnique so t hat you'll be able t o m odify it t o fit t he part icular
requirem ent s of your own applicat ions.)
Anot her way t o approach t his book is t o j ust read t hrough it wit h no specific problem in m ind. This can help you because it will give you a broader underst anding of t he t hings MySQL can do, so I recom m end t hat you page t hrough t he book occasionally. I t 's a m ore effect ive t ool if you have a general fam iliarit y wit h it and know t he kinds of problem s it addresses. The following paragraphs sum m arize each chapt er, t o help give you an overview of t he book's cont ent s.
Chapt er 1, describes how t o use t he st andard MySQL com m and- line client . m ysql is oft en t he first int erface t o MySQL t hat people use, and it 's im port ant t o know how t o exploit it s
capabilit ies. This program allows you t o issue queries and see t he result s int eract ively, so it 's good for quick experim ent at ion. You can also use it in bat ch m ode t o execut e canned SQL script s or send it s out put int o ot her program s. I n addit ion, t he chapt er discusses ot her ways t o use m ysql, such as how t o num ber out put lines or m ake long lines m ore readable, how t o generat e various out put form at s, and how t o log m ysql sessions.
files t o encapsulat e code for com m only used operat ions, and various ways t o gat her t he param et ers needed for m aking connect ions t o t he server.
Chapt er 3, covers several aspect s of t he SELECT st at em ent , which is t he prim ary vehicle for ret rieving dat a from t he MySQL server: specifying which colum ns and rows you want t o ret rieve, perform ing com parisons, dealing wit h NULL values, select ing one sect ion of a query result , using t em porary t ables, and copying result s int o ot her t ables. Lat er chapt ers cover som e of t hese t opics in m ore det ail, but t his chapt er provides an overview of t he concept s on which t hey depend. You should read it if you need som e int roduct ory background on record select ion, for exam ple, if you don't yet know a lot about SQL.
Chapt er 4, describes how t o deal wit h st ring dat a. I t addresses st ring com parisons, pat t ern m at ching, breaking apart and com bining st rings, dealing wit h case-sensit ivit y issues, and perform ing FULLTEXT searches.
Chapt er 5, shows how t o work wit h t em poral dat a. I t describes MySQL's dat e form at and how t o display dat e values in ot her form at s. I t also covers conversion bet ween different t em poral unit s, how t o perform dat e arit hm et ic t o com put e int ervals or generat e one dat e from anot her, leap- year calculat ions, and how t o use MySQL's special TIMESTAMP colum n t ype.
Chapt er 6, describes how t o put t he rows of a query result in t he order you want . This includes specifying t he sort direct ion, dealing wit h NULL values, account ing for st ring case sensit ivit y, and sort ing by dat es or part ial colum n values. I t also provides exam ples t hat show how t o sort special kinds of values, such as dom ain nam es, I P num bers, and ENUM values.
Chapt er 7, shows t echniques t hat are useful for assessing t he general charact erist ics of a set of dat a, such as how m any values it cont ains or what t he m inim um , m axim um , or average values are.
Chapt er 8, describes how t o alt er t he st ruct ure of t ables by adding, dropping, or m odifying colum ns, and how t o set up indexes.
Chapt er 9, discusses how t o get inform at ion about t he dat a a query ret urns, such as t he num ber of rows or colum ns in t he result , or t he nam e and t ype of each colum n. I t also shows how t o ask MySQL what dat abases and t ables are available or about t he st ruct ure of a t able and it s colum ns.
Chapt er 10, describes how t o t ransfer inform at ion bet ween MySQL and ot her program s. This includes how t o convert files from one form at t o anot her, ext ract or rearrange colum ns in dat afiles, check and validat e dat a, rewrit e values such as dat es t hat oft en com e in a variet y of form at s, and how t o figure out which dat a values cause problem s when you load t hem int o MySQL wit h LOAD DATA.
recent value, how t o resequence a colum n, how t o begin a sequence at a given value, and how t o set up a t able so t hat it can m aint ain m ult iple sequences at once. I t also shows how t o use AUTO_INCREMENT values t o m aint ain a m ast er- det ail relat ionship bet ween t ables,
including som e of t he pit falls t o avoid.
Chapt er 12, shows how t o perform j oins, which are operat ions t hat com bine rows in one t able wit h t hose from anot her. I t dem onst rat es how t o com pare t ables t o find m at ches or
m ism at ches, produce m ast er-det ail list s and sum m aries, enum erat e m any- t o-m any
relat ionships, and updat e or delet e records in one t able based on t he cont ent s of anot her.
Chapt er 13, illust rat es how t o produce descript ive st at ist ics, frequency dist ribut ions,
regressions, and correlat ions. I t also covers how t o random ize a set of rows or pick a row at random from t he set .
Chapt er 14, discusses how t o ident ify, count , and rem ove duplicat e records—and how t o prevent t hem from occurring in t he first place.
Chapt er 15, shows how t o handle m ult iple SQL st at em ent s t hat m ust execut e t oget her as a unit . I t discusses how t o cont rol MySQL's aut o- com m it m ode, how t o com m it or roll back t ransact ions, and dem onst rat es som e workarounds you can use if t ransact ional capabilit ies are unavailable in your version of MySQL.
Chapt er 16, get s you set up t o w rit e w eb-based MySQL script s. Web program m ing allows you t o generat e dynam ic pages or collect inform at ion for st orage in your dat abase. The chapt er discusses how t o configure Apache t o run Perl, PHP, and Pyt hon script s, and how t o configure Tom cat t o run Java script s writ t en using JSP not at ion. I t also provides an overview of t he Java St andard Tag Library ( JSTL) t hat is used heavily in JSP pages in t he following chapt ers.
Chapt er 17, shows how t o use t he result s of queries t o produce various t ypes of HTML st ruct ures, such as paragraphs, list s, t ables, hyperlinks, and navigat ion indexes. I t also describes how t o st ore im ages int o MySQL, ret rieve and display t hem lat er, and how t o send a downloadable result set t o a browser.
Chapt er 18, discusses ways t o obt ain input from users over t he Web and use it t o creat e new dat abase records or as t he basis for perform ing searches. I t deals heavily wit h form
processing, including how t o const ruct form elem ent s, such as radio but t ons, pop- up m enus, or checkboxes, based on inform at ion cont ained in your dat abase.
Chapt er 19, describes how t o writ e web applicat ions t hat rem em ber inform at ion across m ult iple request s, using MySQL for backing st ore. This is useful when you want t o collect inform at ion in st ages, or when you need t o m ake decisions based on what t he user has done earlier.
Appendix B, provides a general overview of JSP and inst allat ion inst ruct ions for t he Tom cat web server. Read t his if you need t o inst all Tom cat or are not fam iliar wit h it , or if you're never w rit t en JSP pages.
Appendix C, list s sources of inform at ion t hat provide addit ional inform at ion about t opics covered in t his book. I t also list s som e books t hat provide int roduct ory background for t he program m ing languages used here.
As you get int o lat er chapt ers, you'll som et im es find recipes t hat assum e a know ledge of t opics covered in earlier chapt ers. This also applies wit hin a chapt er, where lat er sect ions oft en use t echniques discussed earlier in t he chapt er. I f you j um p int o a chapt er and find a recipe t hat uses a t echnique wit h which you're not fam iliar, check t he t able of cont ent s or t he index t o find out where t he t echnique is covered. You should find t hat it 's been explained earlier. For exam ple, if you find t hat a recipe sort s a query result using an ORDER BY clause t hat you don't underst and, t urn t o Chapt er 6, which discusses various sort ing m et hods and explains how t hey work.
Platform Notes
Developm ent of t he code in t his book t ook place under MySQL 3.23 and 4.0. Because new feat ures are added t o MySQL on a regular basis, som e exam ples will not work under older versions. I 've t ried t o point out version dependencies when int roducing such feat ures for t he first t im e.
The MySQL language API m odules t hat I used include DBI 1.20 and up, DBD: : m ysql 2.0901 and up, MySQLdb 0.9 and up, MM.MySQL 2.0.5 and up, and MySQL Connect or/ J 2.0.14. DBI requires Perl 5.004_05 or higher up t hrough DBI 1.20, aft er which it requires Perl 5.005_03 or higher. MySQLdb requires Pyt hon 1.5.6 or higher. MM.MySQL and MySQL Connect or/ J require Java SDK 1.1 or higher.
Language processors include Perl 5.6 and 5.6.1; PHP 3 and 4; Pyt hon 1.5.6, 2.2; and 2.3, and Java SDK 1.3.1. Most PHP script s shown here will run under eit her PHP 3 or PHP 4 ( alt hough I st rongly recom m end PHP 4 over PHP 3) . Script s t hat require PHP 4 are so not ed.
I do not assum e t hat you are using Unix, alt hough t hat is m y own preferred developm ent plat form . Most of t he m at erial here should be applicable bot h t o Unix and Windows. The operat ing syst em s I used m ost for developm ent of t he recipes in t his book were Mac OS X; RedHat Linux 6.2, 7.0, and 7.3; and various versions of Windows ( Me, 98, NT, and 2000) .
Conventions Used in This Book
The following font convent ions have been used t hroughout t he book:
Constant width
Used for program list ings, as w ell as w it hin paragraphs t o refer t o program elem ent s such as variable or funct ion nam es.
Constant width bold
Used t o indicat e t ex t t hat you t ype w hen running com m ands.
Constant
width
italic
Used t o indicat e variable input ; you should subst it ut e a value of your ow n choosing.
I t alic
Used for URLs, host nam es, nam es of dir ect or ies and files, Unix com m ands and opt ions, and occasionally for em phasis.
Com m ands oft en are shown wit h a prom pt t o illust rat e t he cont ext in which t hey are used. Com m ands t hat you issue from t he com m and line are shown wit h a % prom pt :
% chmod 600 my.cnf
That prom pt is one t hat Unix users are used t o seeing, but it doesn't necessarily signify t hat a com m and will work only under Unix. Unless indicat ed ot herwise, com m ands shown wit h a % prom pt generally should work under Windows, t oo.
I f you should run a com m and under Unix as t he root user, t he prom pt is # inst ead:
# chkconfig --add tomcat4
For com m ands t hat are specific only t o Windows, t he C:\> prom pt is used:
C:\> copy C:\mysql\lib\cygwinb19.dll C:\Windows\System
SQL st at em ent s t hat are issued from wit hin t he m ysql client program are shown wit h a
mysql> prom pt and t erm inat ed wit h a sem icolon:
mysql> SELECT * FROM my_table;
mysql> SELECT name, abbrev FROM states ORDER BY name; +---+---+
| name | abbrev | +---+---+ | Alabama | AL | | Alaska | AK | | Arizona | AZ | ...
| West Virginia | WV | | Wisconsin | WI | | Wyoming | WY | +---+---+
Exam ples t hat j ust show t he synt ax for SQL st at em ent s do not include t he mysql> prom pt , but t hey do include sem icolons as necessary t o m ake it clear where st at em ent s end. For exam ple, t his is a single st at em ent :
CREATE TABLE t1 (i INT) SELECT * FROM t2;
But t his exam ple represent s t wo st at em ent s:
CREATE TABLE t1 (i INT); SELECT * FROM t2;
The sem icolon is a not at ional convenience used wit hin m ysql as a st at em ent t erm inat or. But it is not part of SQL it self, so when you issue SQL st at em ent s from wit hin program s t hat you writ e ( for exam ple, using Perl or Java) , you should not include t erm inat ing sem icolons.
This icon indicat es a t ip, suggest ion, or general not e.
The Companion Web Site
MySQL Cookbook has a com panion web sit e t hat you can visit t o obt ain t he source code and
sam ple dat a for exam ples developed t hroughout t his book:
ht t p: / / www.kit ebird.com / m ysql- cookbook/
The m ain soft ware dist ribut ion is nam ed recipes and you'll find m any references t o it t hroughout t he book. You can use it t o save a lot of t yping. For exam ple, when you see a
CREATE TABLE st at em ent in t he book t hat describes what a dat abase t able looks like, you'll
% mysql cookbook < filename
I f you need t o specify MySQL usernam e or password opt ions, put t hem before t he dat abase nam e.
For m ore inform at ion about t he dist ribut ions, see Appendix A.
The Kit ebird sit e also m akes som e of t he exam ples from t he book available online so t hat you can t ry t hem out from your browser.
Comments and Questions
Please address com m ent s and quest ions concerning t his book t o t he publisher:
O'Reilly & Associat es, I nc.
1005 Gravenst ein Highway Nort h
Sebast opol, CA 95472
( 800) 998- 9938 ( in t he Unit ed St at es or Canada)
( 707) 829- 0515 ( int ernat ional/ local)
( 707) 829- 0104 ( fax)
O'Reilly keeps a web page for t his book t hat you can access at :
ht t p: / / www.oreilly.com / cat alog/ m ysqlckbk/
To com m ent or ask t echnical quest ions about t his book, send em ail t o:
bookquest [email protected]
For m ore inform at ion about books, conferences, Resource Cent ers, and t he O'Reilly Net work, see t he O'Reilly web sit e at :
ht t p: / / www.oreilly.com
Additional Resources
cont ains m odules t hat allow dat abase access, web program m ing, and XML processing, t o nam e a few of direct relevance t o t his cookbook. Ext ernal support exist s for t he ot her languages as well, t hough none of t hem current ly enj oys t he sam e level of organizat ion as CPAN. PHP has t he PEAR archive, and Pyt hon has a m odule archive called t he Vault s of Parnassus. For Java, a good st art ing point is Sun's Java sit e. Sit es t hat you can visit t o find m ore inform at ion are shown in t he following t able.
API la ngua ge W he r e t o find e x t e r na l suppor t
Per l ht t p: / / cpan.perl.org/
PHP ht t p: / / pear.php.net /
Pyt hon ht t p: / / www.pyt hon.org/
Java ht t p: / / j ava.sun.com /
Acknowledgments
I 'd like t o t hank m y t echnical reviewers, Tim Allwine, David Lane, Hugh William s, and Just in Zobel. They m ade several helpful suggest ions and correct ions wit h regard t o bot h
organizat ional st ruct ure and t echnical accuracy. Several m em bers of MySQL AB were gracious enough t o add t heir com m ent s: I n part icular, principal MySQL developer Mont y Widenius com bed t he t ext and spot t ed m any problem s. Arj en Lent z, Jani Tolonen, Sergei Golubchik, and Zak Greant reviewed sect ions of t he m anuscript as well. Andy Dust m an, aut hor of t he Pyt hon MySQLdb m odule, and Mark Mat t hews, aut hor of MM.MySQL and MySQL Connect or/ J, also provided feedback. My t hanks t o all for im proving t he m anuscript ; any errors rem aining are m y ow n.
Laurie Pet rycki, execut ive edit or, conceived t he idea for t he book and provided valuable overall edit orial guidance and cat t le-prodding. Lenny Muellner, t ools expert , assist ed in t he conversion of t he m anuscript from m y original form at int o som et hing print able. David Chu act ed as edit orial assist ant . Ellie Volckhausen designed t he cover, which I am happy t o see is rept ilian in nat ure. Linley Dolby served as t he product ion edit or and proofreader, and Colleen Gorm an, Darren Kelly, Jeffrey Holcom b, Brian Sawyer, and Claire Clout ier provided qualit y cont rol.
Thanks t o Todd Greanier and Sean Lahm an of The Baseball Archive for all t heir hard work in put t ing t oget her t he baseball dat abase t hat is used for several of t he exam ples in t his book.
Som e aut hors are able t o com pose t ext product ively while sit t ing at a keyboard, but I writ e bet t er while sit t ing far from a com put er—preferably wit h a cup of coffee. That being so, I 'd like t o acknowledge m y debt t o t he Sow's Ear coffee shop in Verona for providing pleasant
Chapter 1. Using the mysql Client Program
Sect ion 1.1. I nt roduct ion
Sect ion 1.2. Set t ing Up a MySQL User Account
Sect ion 1.3. Creat ing a Dat abase and a Sam ple Table
Sect ion 1.4. St art ing and Term inat ing m ysql
Sect ion 1.5. Specifying Connect ion Param et ers by Using Opt ion Files
Sect ion 1.6. Prot ect ing Opt ion Files
Sect ion 1.7. Mixing Com m and- Line and Opt ion File Param et ers
Sect ion 1.8. What t o Do if m ysql Cannot Be Found
Sect ion 1.9. Set t ing Environm ent Variables
Sect ion 1.10. I ssuing Queries
Sect ion 1.11. Select ing a Dat abase
Sect ion 1.12. Canceling a Part ially Ent ered Query
Sect ion 1.13. Repeat ing and Edit ing Queries
Sect ion 1.14. Using Aut o-Com plet ion for Dat abase and Table Nam es
Sect ion 1.15. Using SQL Variables in Queries
Sect ion 1.16. Telling m ysql t o Read Queries from a File
Sect ion 1.17. Telling m ysql t o Read Queries from Ot her Program s
Sect ion 1.18. Specifying Queries on t he Com m and Line
Sect ion 1.19. Using Copy and Past e as a m ysql I nput Source
Sect ion 1.20. Prevent ing Query Out put from Scrolling off t he Screen
Sect ion 1.21. Sending Query Out put t o a File or t o a Program
Sect ion 1.23. Specifying Arbit rary Out put Colum n Delim it ers
Sect ion 1.24. Producing HTML Out put
Sect ion 1.25. Producing XML Out put
Sect ion 1.26. Suppressing Colum n Headings in Query Out put
Sect ion 1.27. Num bering Query Out put Lines
Sect ion 1.28. Making Long Out put Lines More Readable
Sect ion 1.29. Cont rolling m ysql's Verbosit y Level
Sect ion 1.30. Logging I nt eract ive m ysql Sessions
Sect ion 1.31. Creat ing m ysql Script s from Previously Execut ed Queries
Sect ion 1.32. Using m ysql as a Calculat or
1.1 Introduction
The MySQL dat abase syst em uses a client - server archit ect ure t hat cent ers around t he server, m ysqld. The server is t he program t hat act ually m anipulat es dat abases. Client program s don't do t hat direct ly; rat her, t hey com m unicat e your int ent t o t he server by m eans of queries writ t en in St ruct ured Query Language ( SQL) . The client program or program s are inst alled locally on t he m achine from which you wish t o access MySQL, but t he server can be inst alled anywhere, as long as client s can connect t o it . MySQL is an inherent ly net worked dat abase syst em , so client s can com m unicat e wit h a server t hat is running locally on your m achine or one t hat is running som ewhere else, perhaps on a m achine on t he ot her side of t he planet . Client s can be writ t en for m any different purposes, but each int eract s wit h t he server by connect ing t o it , sending SQL queries t o it t o have dat abase operat ions perform ed, and receiving t he query result s from it .
One such client is t he m ysql program t hat is included in MySQL dist ribut ions. When used int eract ively, m ysql prom pt s for a query, sends it t o t he MySQL server for execut ion, and displays t he result s. This capabilit y m akes m ysql useful in it s own right , but it 's also a valuable t ool t o help you wit h your MySQL program m ing act ivit ies. I t 's oft en convenient t o be able t o quickly review t he st ruct ure of a t able t hat you're accessing from wit hin a script , t o t ry a query before using it in a program t o m ake sure it produces t he right kind of out put , and so fort h. m ysql is j ust right for t hese j obs. m ysql also can be used non- int eract ively, for exam ple, t o read queries from a file or from ot her program s. This allows you t o use it from wit hin script s or cr on j obs or in conj unct ion wit h ot her applicat ions.
This chapt er describes m ysql's capabilit ies so t hat you can use it m ore effect ively. Of course, t o t ry out for yourself t he recipes and exam ples shown in t his book, you'll need a MySQL user account and a dat abase t o work wit h. The first t wo sect ions of t he chapt er describe how t o use m ysql t o set t hese up. For dem onst rat ion purposes, t he exam ples assum e t hat you'll use MySQL as follow s:
•
The MySQL server is running on t he local host .•
Your MySQL usernam e and password are cbuser andcbpass.
•
Your dat abase is nam ed cookbook.1.2 Setting Up a MySQL User Account
1.2.1 Problem
You need t o creat e an account t o use for connect ing t o t he MySQL server running on a given host .
1.2.2 Solution
Use t he GRANT st at em ent t o set up t he MySQL user account . Then use t hat account 's nam e and passw ord t o m ake connect ions t o t he server.
1.2.3 Discussion
Connect ing t o a MySQL server requires a usernam e and password. You can also specify t he nam e of t he host where t he server is running. I f you don't specify connect ion param et ers explicit ly, m ysql assum es default values. For exam ple, if you specify no host nam e, m ysql t ypically assum es t he server is running on t he local host .
The following exam ple shows how t o use t he m ysql program t o connect t o t he server and issue a GRANT st at em ent t hat set s up a user account wit h privileges for accessing a dat abase nam ed cookbook. The argum ent s t o m ysql include - h localhost t o connect t o t he MySQL server running on t he local host , - p t o t ell m ysql t o prom pt for a password, and -u root t o connect as t he MySQL root user. Text t hat you t ype is shown in bold; non-bold t ext is program out put :
% mysql -h localhost -p -u root Enter password: ******
mysql> GRANT ALL ON cookbook.* TO 'cbuser'@'localhost' IDENTIFIED BY
'cbpass';
Query OK, 0 rows affected (0.09 sec) mysql> QUIT
Bye
Aft er you ent er t he m ysql com m and shown on t he first line, if you get a m essage indicat ing t hat t he program cannot be found or t hat it is a bad com m and, see Recipe 1.8. Ot herw ise, when m ysql print s t he password prom pt , ent er t he MySQL root password where you see t he
******. ( I f t he MySQL root user has no password, j ust press Ret urn at t he password
prom pt .) Then issue a GRANT st at em ent like t he one shown.
To use a dat abase nam e ot her t han cookbook, subst it ut e it s nam e where you see
cookbook
in t he GRANT st at em ent . Not e t hat you need t o grant privileges for t he dat abase even if t he user account already exist s. However, in t hat case, you'll likely want t o om it t he IDENTIFIEDBY 'cbpass' par t of t he st at em ent , because ot herwise you'll change t hat account 's current
The host nam e part of 'cbuser'@'localhost' indicat es t he host from which you'll be connect ing t o t he MySQL server t o access t he cookbook dat abase. To set up an account t hat will connect t o a server running on t he local host , use localhost, as shown. I f you plan t o m ake connect ions t o t he server from anot her host , subst it ut e t hat host in t he GRANT st at em ent . For exam ple, if you'll be connect ing t o t he server as cbuser from a host nam ed xyz.com , t he
GRANT st at em ent should look like t his:
mysql> GRANT ALL ON cookbook.* TO 'cbuser'@'xyz.com' IDENTIFIED BY
'cbpass';
I t m ay have occurred t o you t hat t here's a bit of a paradox involved in t he procedure j ust described. That is, t o set up a user account t hat can m ake connect ions t o t he MySQL server, you m ust connect t o t he server first so t hat you can issue t he GRANT st at em ent . I 'm assum ing t hat you can already connect as t he MySQL root user, because GRANT can be used only by a user such as root t hat has t he adm inist rat ive privileges needed t o set up ot her user account s. I f you can't connect t o t he server as root, ask your MySQL adm inist rat or t o issue t he GRANT st at em ent for you. Once t hat has been done, you should be able t o use t he new MySQL account t o connect t o t he server, creat e your own dat abase, and proceed from t here on your ow n.
MySQL Accounts and Login Accounts
MySQL account s and login account s for your operat ing syst em are different . For exam ple, t he MySQL root user and t he Unix root user are separat e and have not hing t o do wit h each ot her, even t hough t he usernam e is t he sam e in each case. This m eans t hey are very likely t o have different passwords. I t also m eans you cannot creat e new MySQL account s by creat ing login account s for your operat ing syst em ; use t he GRANT st at em ent inst ead.
1.3 Creating a Database and a Sample Table
1.3.1 Problem
You want t o creat e a dat abase and t o set up t ables wit hin it .
1.3.2 Solution
Use a CREATE DATABASE st at em ent t o creat e a dat abase, a CREATE TABLE st at em ent for each t able you want t o use, and INSERT t o add records t o t he t ables.
1.3.3 Discussion
The GRANT st at em ent used in t he previous sect ion defines privileges for t he cookbook
it . This sect ion shows how t o do t hat , and also how t o creat e a t able and load it wit h som e sam ple dat a t hat can be used for exam ples in t he following sect ions.
Aft er t he cbuser account has been set up, verify t hat you can use it t o connect t o t he MySQL server. Once you've connect ed successfully, creat e t he dat abase. From t he host t hat was nam ed in t he GRANT st at em ent , run t he following com m ands t o do t his ( t he host nam ed aft er - h should be t he host where t he MySQL server is running) :
% mysql -h localhost -p -u cbuser Enter password: cbpass
mysql> CREATE DATABASE cookbook; Query OK, 1 row affected (0.08 sec)
Now you have a dat abase, so you can creat e t ables in it . I ssue t he following st at em ent s t o select cookbook as t he default dat abase, creat e a sim ple t able, and populat e it wit h a few records:[ 1]
[ 1]
I f you don't want t o ent er t he com plet e t ext of t he
INSERT
st at em ent s ( and I don't blam e you) , skip ahead t o Recipe 1.13 for a short cut . And if you don't want t o t ype in any of t he st at em ent s, skip ahead t o Recipe 1.16.mysql> USE cookbook;
mysql> CREATE TABLE limbs (thing VARCHAR(20), legs INT, arms INT); mysql> INSERT INTO limbs (thing,legs,arms) VALUES('human',2,2); mysql> INSERT INTO limbs (thing,legs,arms) VALUES('insect',6,0); mysql> INSERT INTO limbs (thing,legs,arms) VALUES('squid',0,10); mysql> INSERT INTO limbs (thing,legs,arms) VALUES('octopus',0,8); mysql> INSERT INTO limbs (thing,legs,arms) VALUES('fish',0,0);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('centipede',100,0); mysql> INSERT INTO limbs (thing,legs,arms) VALUES('table',4,0);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('armchair',4,2); mysql> INSERT INTO limbs (thing,legs,arms) VALUES('phonograph',0,1); mysql> INSERT INTO limbs (thing,legs,arms) VALUES('tripod',3,0);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('Peg Leg Pete',1,2); mysql> INSERT INTO limbs (thing,legs,arms) VALUES('space alien',NULL,NULL);
The t able is nam ed limbs and cont ains t hree colum ns t o records t he num ber of legs and arm s possessed by various life form s and obj ect s. ( The physiology of t he alien in t he last row is such t hat t he proper values for t he arms and legs colum n cannot be det erm ined; NULL indicat es " unknown value." )
Verify t hat t he t able cont ains what you expect by issuing a SELECT st at em ent :
| centipede | 100 | 0 | | table | 4 | 0 | | armchair | 4 | 2 | | phonograph | 0 | 1 | | tripod | 3 | 0 | | Peg Leg Pete | 1 | 2 | | space alien | NULL | NULL | +---+---+---+ 12 rows in set (0.00 sec)
At t his point , you're all set up wit h a dat abase and a t able t hat can be used t o run som e exam ple queries.
1.4 Starting and Terminating mysql
1.4.1 Problem
You want t o st art and st op t he m ysql program .
1.4.2 Solution
I nvoke m ysql from your com m and prom pt t o st art it , specifying any connect ion param et ers t hat m ay be necessary. To leave m ysql, use a QUIT st at em ent .
1.4.3 Discussion
To st art t he m ysql program , t ry j ust t yping it s nam e at your com m and- line prom pt . I f m ysql st art s up correct ly, you'll see a short m essage, followed by a mysql> prom pt t hat indicat es t he program is ready t o accept queries. To illust rat e, here's what t he welcom e m essage looks like ( t o save space, I won't show it in any furt her exam ples) :
% mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 18427 to server version: 3.23.51-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
I f m ysql t ries t o st art but exit s im m ediat ely wit h an " access denied" m essage, you'll need t o specify connect ion param et ers. The m ost com m only needed param et ers are t he host t o connect t o ( t he host where t he MySQL server runs) , your MySQL usernam e, and a password. For exam ple:
% mysql -h localhost -p -u cbuser Enter password: cbpass
I f you don't have a MySQL usernam e and password, you need t o obt ain perm ission t o use t he MySQL server, as described earlier in Recipe 1.2.
The synt ax and default values for t he connect ion param et er opt ions are shown in t he following t able. These opt ions have bot h a single-dash short form and a double-dash long form .
Pa r a m e t e r t ype Opt ion syn t a x for m s D e fa u lt va lu e
Host nam e - h
hostname
- - host=
hostname
localhost
Usernam e - u
username
- - user=
username
Your login nam ePassword - p- - password None
As t he t able indicat es, t here is no default password. To supply one, use - - password or -p, t hen ent er your password when m ysql prom pt s you for it :
%
mysql -p
Enter password:
enter your password here
I f you like, you can specify t he password direct ly on t he com m and line by using eit her -p
password
( not e t hat t here is no space aft er t he -p) or - - password=password
. I don't recom m end doing t his on a m ult iple- user m achine, because t he password m ay be visible m om ent arily t o ot her users who are running t ools such as ps t hat report process inform at ion.I f you get an error m essage t hat m ysql cannot be found or is an invalid com m and when you t ry t o invoke it , t hat m eans your com m and int erpret er doesn't know where m ysql is inst alled. See Recipe 1.8.
To t erm inat e a m ysql session, issue a QUIT st at em ent :
mysql> QUIT
You can also t erm inat e t he session by issuing an EXIT st at em ent or ( under Unix) by t yping Ct r l- D.
The way you specify connect ion param et ers for m ysql also applies t o ot her MySQL program s such as m ysqldum p and m ysqladm in. For exam ple, som e of t he act ions t hat m ysqladm in can perform are available only t o t he MySQL root account , so you need t o specify nam e and password opt ions for t hat user:
[image:22.612.85.526.157.232.2]1.5 Specifying Connection Parameters by Using Option Files
1.5.1 Problem
You don't want t o t ype connect ion param et ers on t he com m and line every t im e you invoke m ysql.
1.5.2 Solution
Put t he param et ers in an opt ion file.
1.5.3 Discussion
To avoid ent ering connect ion param et ers m anually, put t hem in an opt ion file for m ysql t o read aut om at ically. Under Unix, your personal opt ion file is nam ed .m y.cnf in your hom e direct ory. There are also sit e- wide opt ion files t hat adm inist rat ors can use t o specify
param et ers t hat apply globally t o all users. You can use / et c/ m y.cnf or t he m y.cnf file in t he MySQL server's dat a direct ory. Under Windows, t he opt ion files you can use are C: \ m y.cnf, t he m y.ini file in your Windows syst em direct ory, or m y.cnf in t he server's dat a direct ory.
Windows m ay hide filenam e ext ensions when displaying files, so a file nam ed m y.cnf m ay appear t o be nam ed j ust m y. Your version of Windows m ay allow you t o disable ext ension- hiding. Alt ernat ively, issue a DIR com m and in a DOS window t o see full nam es.
The following exam ple illust rat es t he form at used t o writ e MySQL opt ion files:
# general client program connection options [client]
host=localhost user=cbuser password=cbpass
# options specific to the mysql program [mysql]
no-auto-rehash
# specify pager for interactive mode pager=/usr/bin/less
This form at has t he following general charact erist ics:
doesn't t ake any value ( such as for t he no-auto-rehash opt ion) , t he nam e is list ed by it self wit h no t railing
=value
part .•
I f you don't need som e part icular param et er, j ust leave out t he corresponding line. For exam ple, if you norm ally connect t o t he default host (localhost) , you don't need
any host line. I f your MySQL usernam e is t he sam e as your operat ing syst em login nam e, you can om it t he user line.•
I n opt ion files, only t he long form of an opt ion is allowed. This is in cont rast t o com m and lines, where opt ions oft en can be specified using a short form or a long form . For exam ple, t he host nam e can be given using eit her - hhostname
or -host=
hostname
on t he com m and line; in an opt ion file, only host=hostname
is allow ed.•
Opt ions oft en are used for connect ion param et ers ( such as host, user, andpassword) . However, t he file can specify opt ions t hat have ot her purposes. The
pager opt ion shown for t he [mysql] group specifies t he paging program t hat m ysql
should use for displaying out put in int eract ive m ode. I t has not hing t o do wit h how t he program connect s t o t he server.
•
The usual group for specifying client connect ion param et ers is [client]. This group act ually is used by all t he st andard MySQL client s, so by creat ing an opt ion file t o use w it h m ysql, you m ake it easier t o invoke ot her program s such as m ysqldum p and m ysqladm in as well.•
You can define m ult iple groups in an opt ion file. A com m on convent ion is for aprogram t o look for param et ers in t he [client] group and in t he group nam ed aft er t he program it self. This provides a convenient way t o list general client param et ers t hat you want all client program s t o use, but st ill be able t o specify opt ions t hat apply only t o a part icular program . The preceding sam ple opt ion file illust rat es t his
convent ion for t he m ysql program , which get s general connect ion param et ers from t he
[client] group and also picks up t he no-auto-rehash and pager opt ions from t he
[mysql] group. ( I f you put t he m ysql- specific opt ions in t he [client] group, t hat
will result in " unknown opt ion" errors for all ot her program s t hat use t he [client] group and t hey won't run properly.)
•
I f a param et er is specified m ult iple t im es in an opt ion file, t he last value found t akes precedence. This m eans t hat norm ally you should list any program - specific groups aft er t he [client] group so t hat if t here is any overlap in t he opt ions set by t he t wo groups, t he m ore general opt ions will be overridden by t he program -specific values.•
Lines beginning w it h # or; charact ers are ignored as com m ent s. Blank lines are
ignored, t oo.
•
Opt ion files m ust be plain t ext files. I f you creat e an opt ion file w it h a w ord processor t hat uses som e non- t ext form at by default , be sure t o save t he file explicit ly as t ext . Windows users especially should t ake not e of t his.I f you want t o find out which opt ions will be t aken from opt ion files by m ysql, use t his com m and:
% mysql --print-defaults
You can also use t he m y_print _default s ut ilit y, which t akes as argum ent s t he nam es of t he opt ion file groups t hat it should read. For exam ple, m ysql looks in bot h t he [client] and
[mysql] groups for opt ions, so you can check which values it will t ake from opt ion files like
t his:
% my_print_defaults client mysql
1.6 Protecting Option Files
1.6.1 Problem
Your MySQL usernam e and password are st ored in your opt ion file, and you don't want ot her users reading it .
1.6.2 Solution
Change t he file's m ode t o m ake it accessible only by you.
1.6.3 Discussion
I f you use a m ult iple- user operat ing syst em such as Unix, you should prot ect your opt ion file t o prevent ot her users from finding out how t o connect t o MySQL using your account . Use chm od t o m ake t he file privat e by set t ing it s m ode t o allow access only by yourself:
% chmod 600 .my.cnf
1.7 Mixing Command-Line and Option File Parameters
1.7.1 Problem
You'd rat her not st ore your MySQL password in an opt ion file, but you don't want t o ent er your usernam e and server host m anually.
1.7.2 Solution
Put t he usernam e and host in t he opt ion file, and specify t he password int eract ively when you invoke m ysql; it looks bot h in t he opt ion file and on t he com m and line for connect ion
param et ers. I f an opt ion is specified in bot h places, t he one on t he com m and line t akes precedence.
m ysql first reads your opt ion file t o see what connect ion param et ers are list ed t here, t hen
checks t he com m and line for addit ional param et ers. This m eans you can specify som e opt ions one way, and som e t he ot her way.
Com m and- line param et ers t ake precedence over param et ers found in your opt ion file, so if for som e reason you need t o override an opt ion file param et er, j ust specify it on t he com m and line. For exam ple, you m ight list your regular MySQL usernam e and password in t he opt ion file for general purpose use. I f you need t o connect on occasion as t he MySQL root user, specify t he user and password opt ions on t he com m and line t o override t he opt ion file values:
% mysql -p -u root
To explicit ly specify " no password" when t here is a non- em pt y password in t he opt ion file, use - p on t he com m and line, and t hen j ust press Ret urn when m ysql prom pt s you for t he
password:
%
mysql -p
Enter password:
press Return here
1.8 What to Do if mysql Cannot Be Found
1.8.1 Problem
When you invoke m ysql from t he com m and line, your com m and int erpret er can't find it .
1.8.2 Solution
Add t he direct ory where m ysql is inst alled t o your PATH set t ing. Then you'll be able t o run m ysql from any direct ory easily.
1.8.3 Discussion
I f your shell or com m and int erpret er can't find m ysql when you invoke it , you'll see som e sort of error m essage. I t m ay look like t his under Unix:
% mysql
mysql: Command not found.
Or like t his under Windows:
C:\> mysql
One way t o t ell your shell where t o find m ysql is t o t ype it s full pat hnam e each t im e you run it . The com m and m ight look like t his under Unix:
% /usr/local/mysql/bin/mysql
Or like t his under Windows:
C:\> C:\mysql\bin\mysql
Typing long pat hnam es get s t iresom e pret t y quickly, t hough. You can avoid doing so by changing int o t he direct ory where m ysql is inst alled before you run it . However, I recom m end t hat you not do t hat . I f you do, t he inevit able result is t hat you'll end up put t ing all your dat afiles and query bat ch files in t he sam e direct ory as m ysql, t hus unnecessarily clut t ering up what should be a locat ion int ended only for program s.
A bet t er solut ion is t o m ake sure t hat t he direct ory where m ysql is inst alled is included in t he
PATH environm ent variable t hat list s pat hnam es of direct ories where t he shell looks for
com m ands. ( See Recipe 1.9.) Then you can invoke m ysql from any direct ory by ent ering j ust it s nam e, and your shell will be able t o find it . This elim inat es a lot of unnecessary pat hnam e t yping. An addit ional benefit is t hat because you can easily run m ysql from anywhere, you will have no need t o put your dat afiles in t he sam e direct ory where m ysql is locat ed. When you're not operat ing under t he burden of running m ysql from a part icular locat ion, you'll be free t o organize your files in a way t hat m akes sense t o you, not in a way im posed by som e art ificial necessit y. For exam ple, you can creat e a direct ory under your hom e direct ory for each dat abase you have and put t he files associat ed wit h each dat abase in t he appropriat e direct ory.
I 've point ed out t he im port ance of t he search pat h here because I receive m any quest ions from people who aren't aware of t he exist ence of such a t hing, and who consequent ly t ry t o do all t heir MySQL- relat ed work in t he bin direct ory where m ysql is inst alled. This seem s
part icularly com m on am ong Windows users. Perhaps t he reason is t hat , except for Windows NT and it s derivat ives, t he Windows Help applicat ion seem s t o be silent on t he subj ect of t he com m and int erpret er search pat h or how t o set it . ( Apparent ly, Windows Help considers it dangerous for people t o know how t o do som et hing useful for t hem selves.)
Anot her way for Windows users t o avoid t yping t he pat hnam e or changing int o t he m ysql direct ory is t o creat e a short cut and place it in a m ore convenient locat ion. That has t he advant age of m aking it easy t o st art up m ysql j ust by opening t he short cut . To specify com m and- line opt ions or t he st art up direct ory, edit t he short cut 's propert ies. I f you don't always invoke m ysql wit h t he sam e opt ions, it m ight be useful t o creat e a short cut
corresponding t o each set of opt ions you need—for exam ple, one short cut t o connect as an ordinary user for general work and anot her t o connect as t he MySQL root user for
1.9 Setting Environment Variables
1.9.1 Problem
You need t o m odify your operat ing environm ent , for exam ple, t o change your shell's PATH set t ing.
1.9.2 Solution
Edit t he appropriat e shell st art up file. Under Windows NT- based syst em s, anot her alt ernat ive is t o use t he Syst em cont rol panel.
1.9.3 Discussion
The shell or com m and int erpret er you use t o run program s from t he com m and- line prom pt includes an environm ent in which you can st ore variable values. Som e of t hese variables are used by t he shell it self. For exam ple, it uses PATH t o det erm ine which direct ories t o look in for program s such as m ysql. Ot her variables are used by ot her program s ( such as PERL5LIB, which t ells Perl where t o look for library files used by Perl script s) .
Your shell det erm ines t he synt ax used t o set environm ent variables, as well as t he st art up file in w hich t o place t he set t ings. Typical st art up files for various shells are shown in t he following t able. I f you've never looked t hrough your shell's st art up files, it 's a good idea t o do so t o fam iliarize yourself wit h t heir cont ent s.
Sh e ll Possible st a r t u p file s
csh, t csh .login, .cshrc, .t cshrc
sh, bash, ksh .profile .bash_profile, .bash_login, .bashrc
DOS prom pt C: \ AUTOEXEC.BAT
The following exam ples show how t o set t he PATH variable so t hat it includes t he direct ory where t he m ysql program is inst alled. The exam ples assum e t here is an exist ing PATH set t ing in one of your st art up files. I f you have no PATH set t ing current ly, sim ply add t he appropriat e line or lines t o one of t he files.
I f you're reading t his sect ion because you've been referred here from anot her chapt er, you'll probably be m ore int erest ed in changing som e variable ot her t han PATH. The inst ruct ions are sim ilar because you use t he sam e synt ax.
The PATH variable list s t he pat hnam es for one or m ore direct ories. I f an environm ent
variable's value consist s of m ult iple pat hnam es, it 's convent ional under Unix t o separat e t hem using t he colon charact er (
:) . Under Windows, pat hnam es m ay cont ain colons, so t he
[image:28.612.83.526.417.489.2]To set t he value of PATH, use t he inst ruct ions t hat pert ain t o your shell:
•
For csh or t csh, look for a setenv PATH com m and in your st art up files, t hen add t he appropriat e direct ory t o t he line. Suppose your search pat h is set by a line like t his in your .login file:setenv PATH /bin:/usr/bin:/usr/local/bin
I f m ysql is inst alled in / usr/ local/ m ysql/ bin, add t hat direct ory t o t he search pat h by changing t he setenv line t o look like t his:
setenv PATH /usr/local/mysql/bin:/bin:/usr/bin:/usr/local/bin
I t 's also possible t hat your pat h will be set wit h set path, which uses different synt ax:
set path = (/usr/local/mysql/bin /bin /usr/bin /usr/local/bin)
•
For a shell in t he Bourne shell fam ily such as sh, bash, or ksh, look in your st art up files for a line t hat set s up and export s t he PATH variable:export PATH=/bin:/usr/bin:/usr/local/bin
The assignm ent and t he export m ight be on separat e lines:
PATH=/bin:/usr/bin:/usr/local/bin export PATH
Change t he set t ing t o t his:
export PATH=/usr/local/mysql/bin:/bin:/usr/bin:/usr/local/bin
Or:
PATH=/usr/local/mysql/bin:/bin:/usr/bin:/usr/local/bin export PATH
•
Under Windows, check for a line t hat set s t he PATH variable in your AUTOEXEC.BAT file. I t m ight look like t his:PATH=C:\WINDOWS;C:\WINDOWS\COMMAND
Or like t his:
Change t he PATH value t o include t he direct ory where m ysql is inst alled. I f t his is C: \ m ysql\ bin, t he result ing
PATH set t ing looks like t his:
PATH=C:\mysql\bin;C:\WINDOWS;C:\WINDOWS\COMMAND
Or:
SET PATH=C:\mysql\bin;C:\WINDOWS;C:\WINDOWS\COMMAND
•
Under Windows NT- based syst em s, anot her way t o change t he PATH value is t o use t he Syst em cont rol panel ( use it s Environm ent or Advanced t ab, whichever is present ) . I n ot her versions of Windows, you can use t he Regist ry Edit or applicat ion.Unfort unat ely, t he nam e of t he Regist ry Edit or key t hat cont ains t he pat h value seem s t o vary am ong versions of Windows. For exam ple, on t he Windows m achines t hat I use, t he key has one nam e under Windows Me and a different nam e under Windows 98; under Windows 95, I couldn't find t he key at all. I t 's probably sim pler j ust t o edit AUTOEXEC.BAT.
Aft er set t ing an environm ent variable, you'll need t o cause t he m odificat ion t o t ake effect . Under Unix, you can log out and log in again. Under Windows, if you set PATH using t he Syst em cont rol panel, you can sim ply open a new DOS window. I f you edit ed AUTOEXEC.BAT inst ead, rest art t he m achine.
1.10 Issuing Queries
1.10.1 Problem
You've st art ed m ysql and now you w ant t o send queries t o t he MySQL server.
1.10.2 Solution
Just t ype t hem in, but be sure t o let m ysql know where each one ends.
1.10.3 Discussion
To issue a query at t he mysql> prom pt , t ype it in, add a sem icolon ( ;) at t he end t o signify t he end of t he st at em ent , and press Ret urn. An explicit st at em ent t erm inat or is necessary; m ysql doesn't int erpret Ret urn as a t erm inat or because it 's allowable t o ent er a st at em ent using m ult iple input lines. The sem icolon is t he m ost com m on t erm inat or, but you can also use
\g ( " go" ) as a synonym for t he sem icolon. Thus, t he following exam ples are equivalent ways
of issuing t he sam e query, even t hough t hey are ent ered different ly and t erm inat ed different ly:[ 2]
[ 2]
mysql> SELECT NOW( ); +---+ | NOW( ) | +---+ | 2001-07-04 10:27:23 | +---+ mysql> SELECT
-> NOW( )\g
+---+ | NOW( ) | +---+ | 2001-07-04 10:27:28 | +---+
Not ice for t he second query t hat t he prom pt changes from mysql> t o
-> on t he second input
line. m ysql changes t he prom pt t his way t o let you know t hat it 's st ill wait ing t o see t he query t erm inat or.Be sure t o underst and t hat neit her t he ; charact er nor t he
\g sequence t hat serve as query
t erm inat ors are part of t he query it self. They're convent ions used by t he m ysql program , which recognizes t hese t erm inat ors and st rips t hem from t he input before sending t he query t o t he MySQL server. I t 's im port ant t o rem em ber t his when you writ e your own program s t hat send queries t o t he server ( as we'll begin t o do in t he next chapt er) . I n t hat cont ext , you don't include any t erm inat or charact ers; t he end of t he query st ring it self signifies t he end of t he query. I n fact , adding a t erm inat or m ay well cause t he query t o fail wit h an error.1.11 Selecting a Database
1.11.1 Problem
You want t o t ell m ysql which dat abase t o use.
1.11.2 Solution
Nam e t he dat abase on t he m ysql com m and line or issue a USE st at em ent from wit hin m ysql.
1.11.3 Discussion
When you issue a query t hat refers t o a t able ( as m ost queries do) , you need t o indicat e which dat abase t he t able is part of. One way t o do so is t o use a fully qualified t able reference t hat begins wit h t he dat abase nam e. ( For exam ple, cookbook.limbs refers t o t he limbs t able in t he cookbook dat abase.) As a convenience, MySQL also allows you t o select a default
( current ) dat abase so t hat you can refer t o it s t ables wit hout explicit ly specifying t he dat abase nam e each t im e. You can specify t he dat abase on t he com m and line when you st art m ysql:
% mysql cookbook
% mysql -h host -p -u user cookbook
I f you've already st art ed a m ysql session, you can select a dat abase ( or swit ch t o a different one) by issuing a USE st at em ent :
mysql> USE cookbook; Database changed
I f you've forgot t en or are not sure which dat abase is t he current one ( which can happen easily if you're using m ult iple dat abases and swit ching bet ween t hem several t im es during t he course of a m ysql session) , use t he following st at em ent :
mysql> SELECT DATABASE( ); +---+
| DATABASE() | +---+ | cookbook | +---+
DATABASE( ) is a funct ion t hat ret urns t he nam e of t he current dat abase. I f no dat abase has
been select ed yet , t he funct ion ret urns an em pt y st ring:
mysql> SELECT DATABASE( ); +---+
| DATABASE() | +---+ | | +---+
The STATUS com m and ( and it s synonym , \s) also display t he current dat abase nam e, in addit ional t o several ot her pieces of inform at ion:
mysql> \s ---
Connection id: 5589 Current database: cookbook
Current user: cbuser@localhost Current pager: stdout
Using outfile: ''
Server version: 3.23.51-log Protocol version: 10
Connection: Localhost via UNIX socket Client characterset: latin1
Server characterset: latin1 UNIX socket: /tmp/mysql.sock Uptime: 9 days 39 min 43 sec
Threads: 4 Questions: 42265 Slow queries: 0 Opens: 82 Flush tables: 1 Open tables: 52 Queries per second avg: 0.054
Temporarily Using a Table from Another Database
To use a t able from anot her dat abase t em porarily, you can swit ch t o t hat dat abase and t hen swit ch back when you're done using t he t able. However, you can also use t he t able wit hout swit ching dat abases by referring t o t he t able using it s fully qualified nam e. For exam ple, t o use t he t able other_tbl in anot her dat abase other_db, you can refer t o it as other_db.other_tbl.
1.12 Canceling a Partially Entered Query
1.12.1 Problem
You st art t o ent er a query, t hen decide not t o issue it aft er all.
1.12.2 Solution
Cancel t he query using your line kill charact er or t he \c sequence.
1.12.3 Discussion
I f you change your m ind about issuing a query t hat you're ent ering, cancel it . I f t he query is on a single line, use your line kill charact er t o erase t he ent ire line. ( The part icular charact er t o use depends on your t erm inal set up; for m e, t he charact er is Ct rl-U.) I f you've ent ered a st at em ent over m ult iple lines, t he line kill charact er will erase only t he last line. To cancel t he st at em ent com plet ely, ent er \c and t ype Ret urn. This will ret urn you t o t he mysql> prom pt :
mysql> SELECT * -> FROM limbs -> ORDER BY\c mysql>
Som et im es \c appears t o do not hing ( t hat is, t he mysql> prom pt does not reappear) , which leads t o t he sense t hat you're " t rapped" in a query and can't escape. I f \c is ineffect ive, t he cause usually is t hat you began t yping a quot ed st ring and haven't yet ent ered t he m at ching end quot e t hat t erm inat es t he st ring. Let m ysql's prom pt help you figure out what t o do here. I f t he prom pt has changed from mysql> t o ">, That m eans m ysql is looking for a t erm inat ing double quot e. I f t he prom pt is '> inst ead, m ysql is looking for a t erm inat ing single quot e. Type t he appropriat e m at ching quot e t o end t he st ring, t hen ent er \c followed by Ret urn and you should be okay.
1.13 Repeating and Editing Queries
1.13.1 Problem
1.13.2 Solution
Use m ysql's built - in query edit or.
1.13.3 Discussion
I f you issue a long query only t o find t hat it cont ains a synt ax error, what should you do? Type in t he ent ire correct ed query from scrat ch? No need. m ysql m aint ains a st at em ent hist ory and support s input - line edit ing. This allows you t o recall queries so t hat you can m odify and reissue t hem easily. There are m any, m any edit ing funct ions, but m ost people t end t o use a sm all set of com m ands for t he m aj orit y of t heir edit ing.[ 3] A basic set of useful com m ands is shown in t he following t able. Typically, you use Up Arrow t o recall t he previous line, Left Arrow and Right Arrow t o m ove around wit hin t he line, and Backspace or Delet e t o erase charact ers. To add new charact ers t o t he line, j ust m ove t he cursor t o t he appropriat e spot and t ype t hem in. When you're done edit ing, press Ret urn t o issue t he query ( t he cursor need not be at t he end of t he line when you do t his) .
[ 3]
The input - line edit ing capabilit ies in m ysql are based on t he GNU Readline library. You can read t he docum ent at ion for t his library t o find out m ore about t he m any edit ing funct ions t hat are available. For m ore inform at ion, check t he Bash m anual, available online at ht t p: / / www.gnu.org/ m anual/.
Edit in g Ke y Effe ct of Ke y
Up Arrow Scroll up t hrough st at em ent hist ory Down Arrow Scroll down t hrough st at em ent hist ory Left Arrow Move left wit hin line
Right Arrow Move right wit hin line Ct r l- A Move t o beginning of line Ct r l- E Move t o end of line Backspace Delet e previous charact er Ct r l-