Вы находитесь на странице: 1из 113

Installing MySQL on Linux/UNIX

The recommended way to install MySQL on a Linux system is via RM! MySQL
"# ma$es the %ollowing RMs availa&le %or download on its we& site'
MySQL ( The MySQL data&ase server) which manages data&ases and
ta&les) controls user access) and *rocesses SQL +ueries!
MySQL(client ( MySQL client *rograms) which ma$e it *ossi&le to connect
to and interact with the server!
MySQL(devel ( Li&raries and header ,les that come in handy when
com*iling other *rograms that use MySQL!
MySQL(shared ( Shared li&raries %or the MySQL client!
MySQL(&ench ( #enchmar$ and *er%ormance testing tools %or the MySQL
data&ase server!
The MySQL RMs listed here are all &uilt on a SuS- Linux system) &ut they.ll
usually wor$ on other Linux variants with no di/culty!
Now) %ollow the %ollowing ste*s to *roceed %or installation'
Login to the system using root user!
Switch to the directory containing the RMs'
Install the MySQL data&ase server &y executing the %ollowing command!
Remem&er to re*lace the ,lename in italics with the ,le name o% your RM!
0root1host23 r*m (i MySQL(4!5!6(5!i789!r*m
"&ove command ta$es care o% installing MySQL server) creating a user o%
MySQL) creating necessary con,guration and starting MySQL server
automatically!
:ou can ,nd all the MySQL related &inaries in /usr/&in and /usr/s&in! "ll the
ta&les and data&ases will &e created in /var/li&/mys+l directory!
This is o*tional &ut recommended ste* to install the remaining RMs in the
same manner'
0root1host23 r*m (i MySQL(client(4!5!6(5!i789!r*m
0root1host23 r*m (i MySQL(devel(4!5!6(5!i789!r*m
0root1host23 r*m (i MySQL(shared(4!5!6(5!i789!r*m
0root1host23 r*m (i MySQL(&ench(4!5!6(5!i789!r*m
Installing MySQL on ;indows'
<e%ault installation on any version o% ;indows is now much easier than it
used to &e) as MySQL now comes neatly *ac$aged with an installer! Sim*ly
download the installer *ac$age) un=i* it anywhere) and run setu*!exe!
<e%ault installer setu*!exe will wal$ you through the trivial *rocess and &y
de%ault will install everything under >'?mys+l!
Test the server &y ,ring it u* %rom the command *rom*t the ,rst time! @o to
the location o% the mys+ld server which is *ro&a&ly >'?mys+l?&in) and ty*e'
mys+ld!exe ((console
NAT-' I% you are on NT) then you will have to use mys+ld(nt!exe instead o%
mys+ld!exe
I% all went well) you will see some messages a&out startu* and Inno<#! I% not)
you may have a *ermissions issue! Ma$e sure that the directory that holds
your data is accessi&le to whatever user B*ro&a&ly mys+lC the data&ase
*rocesses run under!
MySQL will not add itsel% to the start menu) and there is no *articularly nice
@UI way to sto* the server either! There%ore) i% you tend to start the server &y
dou&le clic$ing the mys+ld executa&le) you should remem&er to halt the
*rocess &y hand &y using mys+ladmin) Tas$ List) Tas$ Manager) or other
;indows(s*eci,c means!
Deri%ying MySQL Installation'
"%ter MySQL has &een success%ully installed) the &ase ta&les have &een
initiali=ed) and the server has &een started) you can veri%y that all is wor$ing
as it should via some sim*le tests!
Use the mys+ladmin Utility to A&tain Server Status'
Use mys+ladmin &inary to chec$ server version! This &inary would &e
availa&le in /usr/&in on linux and in >'?mys+l?&in on windows!
0root1host23 mys+ladmin ((version
It will *roduce the %ollowing result on Linux! It may vary de*ending on your
installation'
mys+ladmin Der 8!E7 <istri& 4!5!6(5) %or redhat(linux(gnu on i789
I% you do not get such message) then there may &e some *ro&lem in your
installation and you would need some hel* to ,x it!
-xecute sim*le SQL commands using MySQL >lient'
:ou can connect to your MySQL server &y using MySQL client using mys+l
command! "t this moment) you do not need to give any *assword as &y
de%ault it will &e set to &lan$!
So Fust use %ollowing command
0root1host23 mys+l
It should &e rewarded with a mys+lG *rom*t! Now) you are connected to the
MySQL server and you can execute all the SQL command at mys+lG *rom*t
as %ollows'
mys+lG SHA; <"T"#"S-SI
J((((((((((J
K <ata&ase K
J((((((((((J
K mys+l K
K test K
J((((((((((J
E rows in set B5!L7 secC
ost(installation Ste*s'
MySQL shi*s with a &lan$ *assword %or the root MySQL user! "s soon as you
have success%ully installed the data&ase and client) you need to set a root
*assword as %ollows'
0root1host23 mys+ladmin (u root *assword MnewN*asswordMI
Now to ma$e a connection to your MySQL server) you would have to use the
%ollowing command'
0root1host23 mys+l (u root (*
-nter *assword'OOOOOOO
Unix users will also want to *ut your MySQL directory in your "TH) so you
won.t have to $ee* ty*ing out the %ull *ath every time you want to use the
command(line client! Por &ash) it would &e something li$e'
ex*ort "THQR"TH'/usr/&in'/usr/s&in
Running MySQL at &oot time'
I% you want to run MySQL server at &oot time) then ma$e sure you have
%ollowing entry in /etc/rc!local ,le!
/etc/init!d/mys+ld start
"lso)you should have mys+ld &inary in /etc/init!d/ directory!
Running and Shutting down MySQL Server'
Pirst chec$ i% your MySQL server is running or not! :ou can use %ollowing
command to chec$ this'
*s (e% K gre* mys+ld
I% your MyS+l is running) then you will see mys+ld *rocess listed out in your
result! I% server is not running) then you can start it &y using the %ollowing
command'
root1host3 cd /usr/&in
!/sa%eNmys+ld S
Now) i% you want to shut down an already running MySQL server) then you
can do it &y using the %ollowing command'
root1host3 cd /usr/&in
!/mys+ladmin (u root (* shutdown
-nter *assword' OOOOOO
Setting U* a MySQL User "ccount'
Por adding a new user to MySQL) you Fust need to add a new entry to user
ta&le in data&ase mys+l!
#elow is an exam*le o% adding new user guest with S-L->T) INS-RT and
U<"T- *rivileges with the *assword guestLE7I the SQL +uery is'
root1host3 mys+l (u root (*
-nter *assword'OOOOOOO
mys+lG use mys+lI
<ata&ase changed
mys+lG INS-RT INTA user
Bhost) user) *assword)
selectN*riv) insertN*riv) u*dateN*rivC
D"LU-S B.localhost.) .guest.)
"SS;AR<B.guestLE7.C) .:.) .:.) .:.CI
Query AT) L row aUected B5!E5 secC
mys+lG PLUSH RIDIL-@-SI
Query AT) L row aUected B5!5L secC
mys+lG S-L->T host) user) *assword PRAM user ;H-R- user Q .guest.I
J(((((((((((J(((((((((J((((((((((((((((((J
K host K user K *assword K
J(((((((((((J(((((((((J((((((((((((((((((J
K localhost K guest K 9%8cLLV&48%Ece6e K
J(((((((((((J(((((((((J((((((((((((((((((J
L row in set B5!55 secC
;hen adding a new user) remem&er to encry*t the new *assword using
"SS;AR<BC %unction *rovided &y MySQL! "s you can see in the a&ove
exam*le the *assword my*ass is encry*ted to 9%8cLLV&48%Ece6e!
Notice the PLUSH RIDIL-@-S statement! This tells the server to reload the
grant ta&les! I% you don.t use it) then you won.t &e a&le to connect to mys+l
using the new user account at least until the server is re&ooted!
:ou can also s*eci%y other *rivileges to a new user &y setting the values o%
%ollowing columns in user ta&le to .:. when executing the INS-RT +uery or you
can u*date them later using U<"T- +uery!
SelectN*riv
InsertN*riv
U*dateN*riv
<eleteN*riv
>reateN*riv
<ro*N*riv
ReloadN*riv
ShutdownN*riv
rocessN*riv
PileN*riv
@rantN*riv
Re%erencesN*riv
IndexN*riv
"lterN*riv
"nother way o% adding user account is &y using @R"NT SQL commandI
%ollowing exam*le will add user =ara with *assword =araLE7 %or a *articular
data&ase called TUTARI"LS!
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use mys+lI
<ata&ase changed
mys+lG @R"NT S-L->T)INS-RT)U<"T-)<-L-T-)>R-"T-)<RA
(G AN TUTARI"LS!O
(G TA .=ara.1.localhost.
(G I<-NTIPI-< #: .=araLE7.I
This will also create an entry in mys+l data&ase ta&le called user!
NAT-' MySQL does not terminate a command until you give a semi colon BIC
at the end o% SQL command!
The /etc/my!cn% Pile >on,guration'
Most o% the cases) you should not touch this ,le! #y de%ault) it will have
%ollowing entries'
0mys+ld2
datadirQ/var/li&/mys+l
soc$etQ/var/li&/mys+l/mys+l!soc$
0mys+l!server2
userQmys+l
&asedirQ/var/li&
0sa%eNmys+ld2
err(logQ/var/log/mys+ld!log
*id(,leQ/var/run/mys+ld/mys+ld!*id
Here) you can s*eci%y a diUerent directory %or error log) otherwise you should
not change any entry in this ta&le!
"dministrative MySQL >ommand'
Here is the list o% im*ortant MySQL commands) which you will use time to
time to wor$ with MySQL data&ase'
US- <ata&asename ' This will &e used to select a *articular data&ase in
MySQL wor$area!
SHA; <"T"#"S-S' Lists the data&ases that are accessi&le &y the MySQL
<#MS!
SHA; T"#L-S' Shows the ta&les in the data&ase once a data&ase has
&een selected with the use command!
SHA; >ALUMNS PRAM ta&lename' Shows the attri&utes) ty*es o%
attri&utes) $ey in%ormation) whether NULL is *ermitted) de%aults) and other
in%ormation %or a ta&le!
SHA; IN<-X PRAM ta&lename' resents the details o% all indexes on the
ta&le) including the RIM"R: T-:!
SHA; T"#L- ST"TUS LIT- ta&lename?@' Re*orts details o% the MySQL
<#MS *er%ormance and statistics!
MySQL wor$s very well in com&ination o% various *rogramming languages li$e
-RL) >) >JJ) W"D" and H! Aut o% these languages) H is the most *o*ular
one &ecause o% its we& a**lication develo*ment ca*a&ilities!
This tutorial %ocuses heavily on using MySQL in a H environment! I% you are
interested in MySQL with -RL) then you can loo$ into -RL and MySQL
Tutorial!
H *rovides various %unctions to access MySQL data&ase and to mani*ulate
data records inside MySQL data&ase! :ou would re+uire to call H %unctions
in the same way you call any other H %unction!
The H %unctions %or use with MySQL have the %ollowing general %ormat'
mys+lN%unctionBvalue)value)!!!CI
The second *art o% the %unction name is s*eci,c to the %unction) usually a
word that descri&es what the %unction does! The %ollowing are two o% the
%unctions) which we will use in our tutorial!
mys+liNconnectBRconnectCI
mys+liN+ueryBRconnect)MSQL statementMCI
Pollowing exam*le shows a generic sysntax o% H to call any MySQL
%unction!
XhtmlG
XheadG
XtitleGH with MySQLX/titleG
X/headG
X&odyG
XY*h*
Rretval Q mys+lN%unctionBvalue) 0value)!!!2CI
i%B ZRretval C
[
die B M-rror' a related error messageM CI
\
// Atherwise MySQL or H Statements
YG
X/&odyG
X/htmlG
Starting %rom next cha*ter) we will see all the im*ortant MySQL %unctionality
along with H!
MySQL >onnection using mys+l &inary'
:ou can esta&lish MySQL data&ase using mys+l &inary at command *rom*t!
-xam*le'
Here is a sim*le exam*le to connect to MySQL server %rom command *rom*t'
0root1host23 mys+l (u root (*
-nter *assword'OOOOOO
This will give you mys+lG command *rom*t where you will &e a&le to execute
any SQL command! Pollowing is the result o% a&ove command'
;elcome to the MySQL monitor! >ommands end with I or ?g!
:our MySQL connection id is E84V]95 to server version' 4!5!6
Ty*e .hel*I. or .?h. %or hel*! Ty*e .?c. to clear the &uUer!
In a&ove exam*le) we have used root as a user &ut you can use any other
user! "ny user will &e a&le to *er%orm all the SQL o*erations) which are
allowed to that user!
:ou can disconnect %rom MySQL data&ase any time using exit command at
mys+lG *rom*t!
mys+lG exit
#ye
MySQL >onnection using H Scri*t'
H *rovides mys+lNconnectBC %unction to o*en a data&ase connection! This
%unction ta$es ,ve *arameters and returns a MySQL lin$ identi,er on success
or P"LS- on %ailure!
Syntax'
connection mys+lNconnectBserver)user)*asswd)newNlin$)clientN^agCI
arameter <escri*tion
serverA*tional ( The host name running data&ase server! I% not s*eci,ed)
then de%ault value is localhost'7579!
user A*tional ( The username accessing the data&ase! I% not s*eci,ed) then
de%ault is the name o% the user that owns the server *rocess!
*asswd A*tional ( The *assword o% the user accessing the data&ase! I%
not s*eci,ed) then de%ault is an em*ty *assword!
newNlin$ A*tional ( I% a second call is made to mys+lNconnectBC with the
same arguments) no new connection will &e esta&lishedI instead) the
identi,er o% the already o*ened connection will &e returned!
clientN^ags A*tional ( " com&ination o% the %ollowing constants'
M:SQLN>LI-NTNSSL ( Use SSL encry*tion
M:SQLN>LI-NTN>AMR-SS ( Use com*ression *rotocol
M:SQLN>LI-NTNI@NAR-NS">- ( "llow s*ace a%ter %unction names
M:SQLN>LI-NTNINT-R">TID- ( "llow interactive timeout seconds o%
inactivity &e%ore closing the connection
:ou can disconnect %rom MySQL data&ase anytime using another H
%unction mys+lNcloseBC! This %unction ta$es a single *arameter) which is a
connection returned &y mys+lNconnectBC %unction!
Syntax'
&ool mys+lNclose B resource Rlin$Nidenti,er CI
I% a resource is not s*eci,ed then last o*ened data&ase is closed! This
%unction returns true i% it closes connection success%ully otherwise it returns
%alse!
-xam*le'
Try out the %ollowing exam*le to connect to a MySQL server'
XhtmlG
XheadG
XtitleG>onnecting MySQL ServerX/titleG
X/headG
X&odyG
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .guest.I
Rd&*ass Q .guestLE7.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
echo .>onnected success%ully.I
mys+lNcloseBRconnCI
YG
X/&odyG
X/htmlG
>reate <ata&ase using mys+ladmin'
:ou would need s*ecial *rivileges to create or to delete a MySQL data&ase!
So assuming you have access to root user) you can create any data&ase
using mys+l mys+ladmin &inary!
-xam*le'
Here is a sim*le exam*le to create data&ase called TUTARI"LS'
0root1host23 mys+ladmin (u root (* create TUTARI"LS
-nter *assword'OOOOOO
This will create a MySQL data&ase TUTARI"LS!
>reate <ata&ase using H Scri*t'
H uses mys+lN+uery %unction to create or delete a MySQL data&ase! This
%unction ta$es two *arameters and returns TRU- on success or P"LS- on
%ailure!
Syntax'
&ool mys+lN+ueryB s+l) connection CI
arameter <escri*tion
s+l Re+uired ( SQL +uery to create or delete a MySQL data&ase
connection A*tional ( i% not s*eci,ed) then last o*ened connection &y
mys+lNconnect will &e used!
-xam*le'
Try out the %ollowing exam*le to create a data&ase'
XhtmlG
XheadG
XtitleG>reating MySQL <ata&aseX/titleG
X/headG
X&odyG
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
echo .>onnected success%ullyX&r /G.I
Rs+l Q .>R-"T- <"T"#"S- TUTARI"LS.I
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not create data&ase' . ! mys+lNerrorBCCI
\
echo M<ata&ase TUTARI"LS created success%ully?nMI
mys+lNcloseBRconnCI
YG
X/&odyG
X/htmlG
<ro* <ata&ase using mys+ladmin'
:ou would need s*ecial *rivileges to create or to delete a MySQL data&ase!
So assuming you have access to root user) you can create any data&ase
using mys+l mys+ladmin &inary!
#e care%ul while deleting any data&ase &ecause it will lose your all the data
availa&le in your data&ase!
Here is an exam*le to delete a data&ase created in *revious cha*ter'
0root1host23 mys+ladmin (u root (* dro* TUTARI"LS
-nter *assword'OOOOOO
This will give you a warning and it will con,rm i% you really want to delete this
data&ase or not!
<ro**ing the data&ase is *otentially a very &ad thing to do!
"ny data stored in the data&ase will &e destroyed!
<o you really want to dro* the .TUTARI"LS. data&ase 0y/N2 y
<ata&ase MTUTARI"LSM dro**ed
<ro* <ata&ase using H Scri*t'
H uses mys+lN+uery %unction to create or delete a MySQL data&ase! This
%unction ta$es two *arameters and returns TRU- on success or P"LS- on
%ailure!
Syntax'
&ool mys+lN+ueryB s+l) connection CI
arameter <escri*tion
s+l Re+uired ( SQL +uery to create or delete a MySQL data&ase
connection A*tional ( i% not s*eci,ed) then last o*ened connection &y
mys+lNconnect will &e used!
-xam*le'
Try out the %ollowing exam*le to delete a data&ase'
XhtmlG
XheadG
XtitleG<eleting MySQL <ata&aseX/titleG
X/headG
X&odyG
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
echo .>onnected success%ullyX&r /G.I
Rs+l Q .<RA <"T"#"S- TUTARI"LS.I
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not delete data&ase' . ! mys+lNerrorBCCI
\
echo M<ata&ase TUTARI"LS deleted success%ully?nMI
mys+lNcloseBRconnCI
YG
X/&odyG
X/htmlG
;"RNIN@' ;hile deleting a data&ase using H scri*t) it does not *rom*t you
%or any con,rmation! So &e care%ul while deleting a MySQL data&ase!
Ance you get connection with MySQL server) it is re+uired to select a
*articular data&ase to wor$ with! This is &ecause there may &e more than
one data&ase availa&le with MySQL Server!
Selecting MySQL <ata&ase %rom >ommand rom*t'
This is very sim*le to select a *articular data&ase %rom mys+lG *rom*t! :ou
can use SQL command use to select a *articular data&ase!
-xam*le'
Here is an exam*le to select data&ase called TUTARI"LS'
0root1host23 mys+l (u root (*
-nter *assword'OOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG
Now) you have selected TUTARI"LS data&ase and all the su&se+uent
o*erations will &e *er%ormed on TUTARI"LS data&ase!
NAT-' "ll the data&ase names) ta&le names) ta&le ,elds name are case
sensitive! So you would have to use *ro*er names while giving any SQL
command!
Selecting MySQL <ata&ase Using H Scri*t'
H *rovides %unction mys+lNselectNd& to select a data&ase! It returns TRU-
on success or P"LS- on %ailure!
Syntax'
&ool mys+lNselectNd&B d&Nname) connection CI
arameter <escri*tion
d&Nname Re+uired ( MySQL <ata&ase name to &e selected
connection A*tional ( i% not s*eci,ed) then last o*ened connection &y
mys+lNconnect will &e used!
-xam*le'
Here is the exam*le showing you how to select a data&ase!
XhtmlG
XheadG
XtitleGSelecting MySQL <ata&aseX/titleG
X/headG
X&odyG
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .guest.I
Rd&*ass Q .guestLE7.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
echo .>onnected success%ully.I
mys+lNselectNd&B .TUTARI"LS. CI
mys+lNcloseBRconnCI
YG
X/&odyG
X/htmlG
ro*erly de,ning the ,elds in a ta&le is im*ortant to the overall o*timi=ation
o% your data&ase! :ou should use only the ty*e and si=e o% ,eld you really
need to useI don.t de,ne a ,eld as L5 characters wide i% you $now you.re only
going to use E characters! These ty*es o% ,elds Bor columnsC are also re%erred
to as data ty*es) a%ter the ty*e o% data you will &e storing in those ,elds!
MySQL uses many diUerent data ty*es &ro$en into three categories' numeric)
date and time) and string ty*es!
Numeric <ata Ty*es'
MySQL uses all the standard "NSI SQL numeric data ty*es) so i% you.re
coming to MySQL %rom a diUerent data&ase system) these de,nitions will loo$
%amiliar to you! The %ollowing list shows the common numeric data ty*es and
their descri*tions'
INT ( " normal(si=ed integer that can &e signed or unsigned! I% signed) the
allowa&le range is %rom (ELV]V879V8 to ELV]V879V]! I% unsigned) the
allowa&le range is %rom 5 to VE6V69]E64! :ou can s*eci%y a width o% u* to LL
digits!
TIN:INT ( " very small integer that can &e signed or unsigned! I% signed)
the allowa&le range is %rom (LE8 to LE]! I% unsigned) the allowa&le range is
%rom 5 to E44! :ou can s*eci%y a width o% u* to V digits!
SM"LLINT ( " small integer that can &e signed or unsigned! I% signed) the
allowa&le range is %rom (7E]98 to 7E]9]! I% unsigned) the allowa&le range is
%rom 5 to 94474! :ou can s*eci%y a width o% u* to 4 digits!
M-<IUMINT ( " medium(si=ed integer that can &e signed or unsigned! I%
signed) the allowa&le range is %rom (8788958 to 878895]! I% unsigned) the
allowa&le range is %rom 5 to L9]]]EL4! :ou can s*eci%y a width o% u* to 6
digits!
#I@INT ( " large integer that can &e signed or unsigned! I% signed) the
allowa&le range is %rom (6EE77]E57984V]]4858 to 6EE77]E57984V]]485]!
I% unsigned) the allowa&le range is %rom 5 to L8VV9]VV5]7]5644L9L4! :ou
can s*eci%y a width o% u* to LL digits!
PLA"TBM)<C ( " ^oating(*oint num&er that cannot &e unsigned! :ou can
de,ne the dis*lay length BMC and the num&er o% decimals B<C! This is not
re+uired and will de%ault to L5)E) where E is the num&er o% decimals and L5 is
the total num&er o% digits Bincluding decimalsC! <ecimal *recision can go to
EV *laces %or a PLA"T!
<AU#L-BM)<C ( " dou&le *recision ^oating(*oint num&er that cannot &e
unsigned! :ou can de,ne the dis*lay length BMC and the num&er o% decimals
B<C! This is not re+uired and will de%ault to L9)V) where V is the num&er o%
decimals! <ecimal *recision can go to 47 *laces %or a <AU#L-! R-"L is a
synonym %or <AU#L-!
<->IM"LBM)<C ( "n un*ac$ed ^oating(*oint num&er that cannot &e
unsigned! In un*ac$ed decimals) each decimal corres*onds to one &yte!
<e,ning the dis*lay length BMC and the num&er o% decimals B<C is re+uired!
NUM-RI> is a synonym %or <->IM"L!
<ate and Time Ty*es'
The MySQL date and time dataty*es are'
<"T- ( " date in ::::(MM(<< %ormat) &etween L555(5L(5L and 6666(LE(
7L! Por exam*le) <ecem&er 75th) L6]7 would &e stored as L6]7(LE(75!
<"T-TIM- ( " date and time com&ination in ::::(MM(<< HH'MM'SS %ormat)
&etween L555(5L(5L 55'55'55 and 6666(LE(7L E7'46'46! Por exam*le) 7'75
in the a%ternoon on <ecem&er 75th) L6]7 would &e stored as L6]7(LE(75
L4'75'55!
TIM-ST"M ( " timestam* &etween midnight) Wanuary L) L6]5 and
sometime in E57]! This loo$s li$e the *revious <"T-TIM- %ormat) only without
the hy*hens &etween num&ersI 7'75 in the a%ternoon on <ecem&er 75th)
L6]7 would &e stored as L6]7LE75L47555 B ::::MM<<HHMMSS C!
TIM- ( Stores the time in HH'MM'SS %ormat!
:-"RBMC ( Stores a year in E(digit or V(digit %ormat! I% the length is s*eci,ed
as E B%or exam*le :-"RBECC) :-"R can &e L6]5 to E596 B]5 to 96C! I% the
length is s*eci,ed as V) :-"R can &e L65L to EL44! The de%ault length is V!
String Ty*es'
"lthough numeric and date ty*es are %un) most data you.ll store will &e in
string %ormat! This list descri&es the common string dataty*es in MySQL!
>H"RBMC ( " ,xed(length string &etween L and E44 characters in length
B%or exam*le >H"RB4CC) right(*added with s*aces to the s*eci,ed length
when stored! <e,ning a length is not re+uired) &ut the de%ault is L!
D"R>H"RBMC ( " varia&le(length string &etween L and E44 characters in
lengthI %or exam*le D"R>H"RBE4C! :ou must de,ne a length when creating a
D"R>H"R ,eld!
#LA# or T-XT ( " ,eld with a maximum length o% 94474 characters! #LA#s
are M#inary Large A&FectsM and are used to store large amounts o% &inary
data) such as images or other ty*es o% ,les! Pields de,ned as T-XT also hold
large amounts o% dataI the diUerence &etween the two is that sorts and
com*arisons on stored data are case sensitive on #LA#s and are not case
sensitive in T-XT ,elds! :ou do not s*eci%y a length with #LA# or T-XT!
TIN:#LA# or TIN:T-XT ( " #LA# or T-XT column with a maximum length o%
E44 characters! :ou do not s*eci%y a length with TIN:#LA# or TIN:T-XT!
M-<IUM#LA# or M-<IUMT-XT ( " #LA# or T-XT column with a maximum
length o% L9]]]EL4 characters! :ou do not s*eci%y a length with M-<IUM#LA#
or M-<IUMT-XT!
LAN@#LA# or LAN@T-XT ( " #LA# or T-XT column with a maximum length
o% VE6V69]E64 characters! :ou do not s*eci%y a length with LAN@#LA# or
LAN@T-XT!
-NUM ( "n enumeration) which is a %ancy term %or list! ;hen de,ning an
-NUM) you are creating a list o% items %rom which the value must &e selected
Bor it can &e NULLC! Por exam*le) i% you wanted your ,eld to contain M"M or M#M
or M>M) you would de,ne your -NUM as -NUM B.".) .#.) .>.C and only those
values Bor NULLC could ever *o*ulate that ,eld!
The ta&le creation command re+uires'
Name o% the ta&le
Names o% ,elds
<e,nitions %or each ,eld
Syntax'
Here is generic SQL syntax to create a MySQL ta&le'
>R-"T- T"#L- ta&leNname BcolumnNname columnNty*eCI
Now we will create %ollowing ta&le in TUTARI"LS data&ase!
tutorialsNt&lB
tutorialNid INT NAT NULL "UTANIN>R-M-NT)
tutorialNtitle D"R>H"RBL55C NAT NULL)
tutorialNauthor D"R>H"RBV5C NAT NULL)
su&missionNdate <"T-)
RIM"R: T-: B tutorialNid C
CI
Here %ew items need ex*lanation'
Pield "ttri&ute NAT NULL is &eing used &ecause we do not want this ,eld to
&e NULL! So i% user will try to create a record with NULL value) then MySQL
will raise an error!
Pield "ttri&ute "UTANIN>R-M-NT tells MySQL to go ahead and add the next
availa&le num&er to the id ,eld!
Teyword RIM"R: T-: is used to de,ne a column as *rimary $ey! :ou can
use multi*le columns se*arated &y comma to de,ne a *rimary $ey!
>reating Ta&les %rom >ommand rom*t'
This is easy to create a MySQL ta&le %rom mys+lG *rom*t! :ou will use SQL
command >R-"T- T"#L- to create a ta&le!
-xam*le'
Here is an exam*le) which creates tutorialsNt&l'
root1host3 mys+l (u root (*
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG >R-"T- T"#L- tutorialsNt&lB
(G tutorialNid INT NAT NULL "UTANIN>R-M-NT)
(G tutorialNtitle D"R>H"RBL55C NAT NULL)
(G tutorialNauthor D"R>H"RBV5C NAT NULL)
(G su&missionNdate <"T-)
(G RIM"R: T-: B tutorialNid C
(G CI
Query AT) 5 rows aUected B5!L9 secC
mys+lG
NAT-' MySQL does not terminate a command until you give a semicolon BIC at
the end o% SQL command!
>reating Ta&les Using H Scri*t'
To create new ta&le in any existing data&ase you would need to use H
%unction mys+lN+ueryBC! :ou will *ass its second argument with *ro*er SQL
command to create a ta&le!
-xam*le'
Here is an exam*le to create a ta&le using H scri*t'
XhtmlG
XheadG
XtitleG>reating MySQL Ta&lesX/titleG
X/headG
X&odyG
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
echo .>onnected success%ullyX&r /G.I
Rs+l Q M>R-"T- T"#L- tutorialsNt&lB M!
MtutorialNid INT NAT NULL "UTANIN>R-M-NT) M!
MtutorialNtitle D"R>H"RBL55C NAT NULL) M!
MtutorialNauthor D"R>H"RBV5C NAT NULL) M!
Msu&missionNdate <"T-) M!
MRIM"R: T-: B tutorialNid CCI MI
mys+lNselectNd&B .TUTARI"LS. CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not create ta&le' . ! mys+lNerrorBCCI
\
echo MTa&le created success%ully?nMI
mys+lNcloseBRconnCI
YG
X/&odyG
X/htmlG
It is very easy to dro* an existing MySQL ta&le) &ut you need to &e very
care%ul while deleting any existing ta&le &ecause data lost will not &e
recovered a%ter deleting a ta&le!
Syntax'
Here is generic SQL syntax to dro* a MySQL ta&le'
<RA T"#L- ta&leNname I
<ro**ing Ta&les %rom >ommand rom*t'
This needs Fust to execute <RA T"#L- SQL command at mys+lG *rom*t!
-xam*le'
Here is an exam*le) which deletes tutorialsNt&l'
root1host3 mys+l (u root (*
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG <RA T"#L- tutorialsNt&l
Query AT) 5 rows aUected B5!8 secC
mys+lG
<ro**ing Ta&les Using H Scri*t'
To dro* an existing ta&le in any data&ase) you would need to use H
%unction mys+lN+ueryBC! :ou will *ass its second argument with *ro*er SQL
command to dro* a ta&le!
-xam*le'
XhtmlG
XheadG
XtitleG>reating MySQL Ta&lesX/titleG
X/headG
X&odyG
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
echo .>onnected success%ullyX&r /G.I
Rs+l Q M<RA T"#L- tutorialsNt&lMI
mys+lNselectNd&B .TUTARI"LS. CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not delete ta&le' . ! mys+lNerrorBCCI
\
echo MTa&le deleted success%ully?nMI
mys+lNcloseBRconnCI
YG
X/&odyG
X/htmlG
To insert data into MySQL ta&le) you would need to use SQL INS-RT INTA
command! :ou can insert data into MySQL ta&le &y using mys+lG *rom*t or
&y using any scri*t li$e H!
Syntax'
Here is generic SQL syntax o% INS-RT INTA command to insert data into
MySQL ta&le'
INS-RT INTA ta&leNname B ,eldL) ,eldE)!!!,eldN C
D"LU-S
B valueL) valueE)!!!valueN CI
To insert string data ty*es) it is re+uired to $ee* all the values into dou&le or
single +uote) %or exam*le'( MvalueM!
Inserting <ata %rom >ommand rom*t'
This will use SQL INS-RT INTA command to insert data into MySQL ta&le
tutorialsNt&l!
-xam*le'
Pollowing exam*le will create 7 records into tutorialsNt&l ta&le'
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG INS-RT INTA tutorialsNt&l
(GBtutorialNtitle) tutorialNauthor) su&missionNdateC
(GD"LU-S
(GBMLearn HM) MWohn oulM) NA;BCCI
Query AT) L row aUected B5!5L secC
mys+lG INS-RT INTA tutorialsNt&l
(GBtutorialNtitle) tutorialNauthor) su&missionNdateC
(GD"LU-S
(GBMLearn MySQLM) M"&dul SM) NA;BCCI
Query AT) L row aUected B5!5L secC
mys+lG INS-RT INTA tutorialsNt&l
(GBtutorialNtitle) tutorialNauthor) su&missionNdateC
(GD"LU-S
(GBMW"D" TutorialM) MSanFayM) .E55](54(59.CI
Query AT) L row aUected B5!5L secC
mys+lG
NAT-' lease note that all the arrow signs B(GC are not *art o% SQL commandI
they are indicating a new line and they are created automatically &y MySQL
*rom*t while *ressing enter $ey without giving a semicolon at the end o%
each line o% the command!
In the a&ove exam*le) we have not *rovided tutorialNid &ecause at the time
o% ta&le creation) we had given "UTANIN>R-M-NT o*tion %or this ,eld! So
MySQL ta$es care o% inserting these I<s automatically! Here) NA;BC is a
MySQL %unction) which returns current date and time!
Inserting <ata Using H Scri*t'
:ou can use same SQL INS-RT INTA command into H %unction
mys+lN+ueryBC to insert data into a MySQL ta&le!
-xam*le'
This exam*le will ta$e three *arameters %rom user and will insert them into
MySQL ta&le'
XhtmlG
XheadG
XtitleG"dd New Record in MySQL <ata&aseX/titleG
X/headG
X&odyG
XY*h*
i%BissetBRNAST0.add.2CC
[
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
i%BZ getNmagicN+uotesNg*cBC C
[
RtutorialNtitle Q addslashes BRNAST0.tutorialNtitle.2CI
RtutorialNauthor Q addslashes BRNAST0.tutorialNauthor.2CI
\
else
[
RtutorialNtitle Q RNAST0.tutorialNtitle.2I
RtutorialNauthor Q RNAST0.tutorialNauthor.2I
\
Rsu&missionNdate Q RNAST0.su&missionNdate.2I
Rs+l Q MINS-RT INTA tutorialsNt&l M!
MBtutorialNtitle)tutorialNauthor) su&missionNdateC M!
MD"LU-S M!
MB.RtutorialNtitle.).RtutorialNauthor.).Rsu&missionNdate.CMI
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not enter data' . ! mys+lNerrorBCCI
\
echo M-ntered data success%ully?nMI
mys+lNcloseBRconnCI
\
else
[
YG
X%orm methodQM*ostM actionQMXY*h* RNHNS-LP YGMG
Xta&le widthQM955M &orderQM5M cells*acingQMLM cell*addingQMEMG
XtrG
Xtd widthQME45MGTutorial TitleX/tdG
XtdG
Xin*ut nameQMtutorialNtitleM ty*eQMtextM idQMtutorialNtitleMG
X/tdG
X/trG
XtrG
Xtd widthQME45MGTutorial "uthorX/tdG
XtdG
Xin*ut nameQMtutorialNauthorM ty*eQMtextM idQMtutorialNauthorMG
X/tdG
X/trG
XtrG
Xtd widthQME45MGSu&mission <ate 0 yyyy(mm(dd 2X/tdG
XtdG
Xin*ut nameQMsu&missionNdateM ty*eQMtextM idQMsu&missionNdateMG
X/tdG
X/trG
XtrG
Xtd widthQME45MG X/tdG
XtdG X/tdG
X/trG
XtrG
Xtd widthQME45MG X/tdG
XtdG
Xin*ut nameQMaddM ty*eQMsu&mitM idQMaddM valueQM"dd TutorialMG
X/tdG
X/trG
X/ta&leG
X/%ormG
XY*h*
\
YG
X/&odyG
X/htmlG
;hile doing data insert) it.s &est *ractice to use %unction
getNmagicN+uotesNg*cBC to chec$ i% current con,guration %or magic +uote is
set or not! I% this %unction returns %alse) then use %unction addslashesBC to add
slashes &e%ore +uotes!
:ou can *ut many validations around to chec$ i% entered data is correct or not
and can ta$e a**ro*riate action!
The SQL S-L->T command is used to %etch data %rom MySQL data&ase! :ou
can use this command at mys+lG *rom*t as well as in any scri*t li$e H!
Syntax'
Here is generic SQL syntax o% S-L->T command to %etch data %rom MySQL
ta&le'
S-L->T ,eldL) ,eldE)!!!,eldN ta&leNnameL) ta&leNnameE!!!
0;H-R- >lause2
0APPS-T M 20LIMIT N2
:ou can use one or more ta&les se*arated &y comma to include various
condition using a ;H-R- clause) &ut ;H-R- clause is an o*tional *art o%
S-L->T command!
:ou can %etch one or more ,elds in a single S-L->T command!
:ou can s*eci%y star BOC in *lace o% ,elds! In this case) S-L->T will return all
the ,elds!
:ou can s*eci%y any condition using ;H-R- clause!
:ou can s*eci%y an oUset using APPS-T %rom where S-L->T will start
returning records! #y de%ault oUset is =ero!
:ou can limit the num&er o% returns using LIMIT attri&ute!
Petching <ata %rom >ommand rom*t'
This will use SQL S-L->T command to %etch data %rom MySQL ta&le
tutorialsNt&l
-xam*le'
Pollowing exam*le will return all the records %rom tutorialsNt&l ta&le'
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG S-L->T O %rom tutorialsNt&l
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
K tutorialNid K tutorialNtitle K tutorialNauthor K su&missionNdate K
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
K L K Learn H K Wohn oul K E55](54(EL K
K E K Learn MySQL K "&dul S K E55](54(EL K
K 7 K W"D" Tutorial K SanFay K E55](54(EL K
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
7 rows in set B5!5L secC
mys+lG
Petching <ata Using H Scri*t'
:ou can use same SQL S-L->T command into H %unction mys+lN+ueryBC!
This %unction is used to execute SQL command and later another H %unction
mys+lN%etchNarrayBC can &e used to %etch all the selected data! This %unction
returns row as an associative array) a numeric array) or &oth! This %unction
returns P"LS- i% there are no more rows!
#elow is a sim*le exam*le to %etch records %rom tutorialsNt&l ta&le!
-xam*le'
Try out the %ollowing exam*le to dis*lay all the records %rom tutorialsNt&l
ta&le!
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rs+l Q .S-L->T tutorialNid) tutorialNtitle)
tutorialNauthor) su&missionNdate
PRAM tutorialsNt&l.I
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not get data' . ! mys+lNerrorBCCI
\
whileBRrow Q mys+lN%etchNarrayBRretval) M:SQLN"SSA>CC
[
echo MTutorial I< '[Rrow0.tutorialNid.2\ X&rG M!
MTitle' [Rrow0.tutorialNtitle.2\ X&rG M!
M"uthor' [Rrow0.tutorialNauthor.2\ X&rG M!
MSu&mission <ate ' [Rrow0.su&missionNdate.2\ X&rG M!
M((((((((((((((((((((((((((((((((X&rGMI
\
echo MPetched data success%ully?nMI
mys+lNcloseBRconnCI
YG
The content o% the rows are assigned to the varia&le Rrow and the values in
row are then *rinted!
NAT-' "lways remem&er to *ut curly &rac$ets when you want to insert an
array value directly into a string!
In a&ove exam*le) the constant M:SQLN"SSA> is used as the second
argument to H %unction mys+lN%etchNarrayBC) so that it returns the row as
an associative array! ;ith an associative array you can access the ,eld &y
using their name instead o% using the index!
H *rovides another %unction called mys+lN%etchNassocBC) which also returns
the row as an associative array!
-xam*le'
Try out the %ollowing exam*le to dis*lay all the records %rom tutorialNt&l ta&le
using mys+lN%etchNassocBC %unction!
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rs+l Q .S-L->T tutorialNid) tutorialNtitle)
tutorialNauthor) su&missionNdate
PRAM tutorialsNt&l.I
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not get data' . ! mys+lNerrorBCCI
\
whileBRrow Q mys+lN%etchNassocBRretvalCC
[
echo MTutorial I< '[Rrow0.tutorialNid.2\ X&rG M!
MTitle' [Rrow0.tutorialNtitle.2\ X&rG M!
M"uthor' [Rrow0.tutorialNauthor.2\ X&rG M!
MSu&mission <ate ' [Rrow0.su&missionNdate.2\ X&rG M!
M((((((((((((((((((((((((((((((((X&rGMI
\
echo MPetched data success%ully?nMI
mys+lNcloseBRconnCI
YG
:ou can also use the constant M:SQLNNUM) as the second argument to H
%unction mys+lN%etchNarrayBC! This will cause the %unction to return an array
with numeric index!
-xam*le'
Try out the %ollowing exam*le to dis*lay all the records %rom tutorialsNt&l ta&le
using M:SQLNNUM argument!
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rs+l Q .S-L->T tutorialNid) tutorialNtitle)
tutorialNauthor) su&missionNdate
PRAM tutorialsNt&l.I
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not get data' . ! mys+lNerrorBCCI
\
whileBRrow Q mys+lN%etchNarrayBRretval) M:SQLNNUMCC
[
echo MTutorial I< '[Rrow052\ X&rG M!
MTitle' [Rrow0L2\ X&rG M!
M"uthor' [Rrow0E2\ X&rG M!
MSu&mission <ate ' [Rrow072\ X&rG M!
M((((((((((((((((((((((((((((((((X&rGMI
\
echo MPetched data success%ully?nMI
mys+lNcloseBRconnCI
YG
"ll the a&ove three exam*les will *roduce the same result!
Releasing Memory'
It.s a good *ractice to release cursor memory at the end o% each S-L->T
statement! This can &e done &y using H %unction mys+lN%reeNresultBC! #elow
is the exam*le to show how it has to &e used!
-xam*le'
Try out the %ollowing exam*le
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rs+l Q .S-L->T tutorialNid) tutorialNtitle)
tutorialNauthor) su&missionNdate
PRAM tutorialsNt&l.I
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not get data' . ! mys+lNerrorBCCI
\
whileBRrow Q mys+lN%etchNarrayBRretval) M:SQLNNUMCC
[
echo MTutorial I< '[Rrow052\ X&rG M!
MTitle' [Rrow0L2\ X&rG M!
M"uthor' [Rrow0E2\ X&rG M!
MSu&mission <ate ' [Rrow072\ X&rG M!
M((((((((((((((((((((((((((((((((X&rGMI
\
mys+lN%reeNresultBRretvalCI
echo MPetched data success%ully?nMI
mys+lNcloseBRconnCI
YG
;hile %etching data) you can write as com*lex SQL as you li$e! rocedure will
remain same as mentioned a&ove!
;e have seen SQL S-L->T command to %etch data %rom MySQL ta&le! ;e can
use a conditional clause called ;H-R- clause to ,lter out results! Using
;H-R- clause) we can s*eci%y a selection criteria to select re+uired records
%rom a ta&le!
Syntax'
Here is generic SQL syntax o% S-L->T command with ;H-R- clause to %etch
data %rom MySQL ta&le'
S-L->T ,eldL) ,eldE)!!!,eldN ta&leNnameL) ta&leNnameE!!!
0;H-R- conditionL 0"N< 0AR22 conditionE!!!!!
:ou can use one or more ta&les se*arated &y comma to include various
conditions using a ;H-R- clause) &ut ;H-R- clause is an o*tional *art o%
S-L->T command!
:ou can s*eci%y any condition using ;H-R- clause!
:ou can s*eci%y more than one conditions using "N< or AR o*erators!
" ;H-R- clause can &e used along with <-L-T- or U<"T- SQL command
also to s*eci%y a condition!
The ;H-R- clause wor$s li$e an i% condition in any *rogramming language!
This clause is used to com*are given value with the ,eld value availa&le in
MySQl ta&le! I% given value %rom outside is e+ual to the availa&le ,eld value in
MySQL ta&le) then it returns that row!
Here is the list o% o*erators) which can &e used with ;H-R- clause!
"ssume ,eld " holds L5 and ,eld # holds E5) then'
A*erator <escri*tion -xam*le
Q >hec$s i% the value o% two o*erands is e+ual or not) i% yes then
condition &ecomes true! B" Q #C is not true!
ZQ >hec$s i% the value o% two o*erands is e+ual or not) i% values are not
e+ual then condition &ecomes true! B" ZQ #C is true!
G >hec$s i% the value o% le%t o*erand is greater than the value o% right
o*erand) i% yes then condition &ecomes true! B" G #C is not true!
X >hec$s i% the value o% le%t o*erand is less than the value o% right
o*erand) i% yes then condition &ecomes true! B" X #C is true!
GQ >hec$s i% the value o% le%t o*erand is greater than or e+ual to the value
o% right o*erand) i% yes then condition &ecomes true! B" GQ #C is not
true!
XQ >hec$s i% the value o% le%t o*erand is less than or e+ual to the value o%
right o*erand) i% yes then condition &ecomes true! B" XQ #C is true!
The ;H-R- clause is very use%ul when you want to %etch selected rows %rom
a ta&le) es*ecially when you use MySQL Woin! Woins are discussed in another
cha*ter!
It is a common *ractice to search records using rimary Tey to ma$e search
%ast!
I% given condition does not match any record in the ta&le) then +uery would
not return any row!
Petching <ata %rom >ommand rom*t'
This will use SQL S-L->T command with ;H-R- clause to %etch selected data
%rom MySQL ta&le tutorialsNt&l!
-xam*le'
Pollowing exam*le will return all the records %rom tutorialsNt&l ta&le %or which
author name is SanFay'
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG S-L->T O %rom tutorialsNt&l ;H-R- tutorialNauthorQ.SanFay.I
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
K tutorialNid K tutorialNtitle K tutorialNauthor K su&missionNdate K
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
K 7 K W"D" Tutorial K SanFay K E55](54(EL K
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
L rows in set B5!5L secC
mys+lG
Unless *er%orming a LIT- com*arison on a string) the com*arison is not case
sensitive! :ou can ma$e your search case sensitive using #IN"R: $eyword as
%ollows'
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG S-L->T O %rom tutorialsNt&l ?
;H-R- #IN"R: tutorialNauthorQ.sanFay.I
-m*ty set B5!5E secC
mys+lG
Petching <ata Using H Scri*t'
:ou can use same SQL S-L->T command with ;H-R- >L"US- into H
%unction mys+lN+ueryBC! This %unction is used to execute SQL command and
later another H %unction mys+lN%etchNarrayBC can &e used to %etch all the
selected data! This %unction returns row as an associative array) a numeric
array) or &oth! This %unction returns P"LS- i% there are no more rows!
-xam*le'
Pollowing exam*le will return all the records %rom tutorialsNt&l ta&le %or which
author name is SanFay'
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rs+l Q .S-L->T tutorialNid) tutorialNtitle)
tutorialNauthor) su&missionNdate
PRAM tutorialsNt&l
;H-R- tutorialNauthorQMSanFayM.I
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not get data' . ! mys+lNerrorBCCI
\
whileBRrow Q mys+lN%etchNarrayBRretval) M:SQLN"SSA>CC
[
echo MTutorial I< '[Rrow0.tutorialNid.2\ X&rG M!
MTitle' [Rrow0.tutorialNtitle.2\ X&rG M!
M"uthor' [Rrow0.tutorialNauthor.2\ X&rG M!
MSu&mission <ate ' [Rrow0.su&missionNdate.2\ X&rG M!
M((((((((((((((((((((((((((((((((X&rGMI
\
echo MPetched data success%ully?nMI
mys+lNcloseBRconnCI
YG
There may &e a re+uirement where existing data in a MySQL ta&le needs to
&e modi,ed! :ou can do so &y using SQL U<"T- command! This will modi%y
any ,eld value o% any MySQL ta&le!
Syntax'
Here is generic SQL syntax o% U<"T- command to modi%y data into MySQL
ta&le'
U<"T- ta&leNname S-T ,eldLQnew(valueL) ,eldEQnew(valueE
0;H-R- >lause2
:ou can u*date one or more ,eld altogether!
:ou can s*eci%y any condition using ;H-R- clause!
:ou can u*date values in a single ta&le at a time!
The ;H-R- clause is very use%ul when you want to u*date selected rows in a
ta&le!
U*dating <ata %rom >ommand rom*t'
This will use SQL U<"T- command with ;H-R- clause to u*date selected
data into MySQL ta&le tutorialsNt&l!
-xam*le'
Pollowing exam*le will u*date tutorialNtitle ,eld %or a record having tutorialNid
as 7!
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG U<"T- tutorialsNt&l
(G S-T tutorialNtitleQ.Learning W"D".
(G ;H-R- tutorialNidQ7I
Query AT) L row aUected B5!5V secC
Rows matched' L >hanged' L ;arnings' 5
mys+lG
U*dating <ata Using H Scri*t'
:ou can use SQL U<"T- command with or without ;H-R- >L"US- into H
%unction mys+lN+ueryBC! This %unction will execute SQL command in similar
way it is executed at mys+lG *rom*t!
-xam*le'
Try out the %ollowing exam*le to u*date tutorialNtitle ,eld %or a record having
tutorialNid as 7!
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rs+l Q .U<"T- tutorialsNt&l
S-T tutorialNtitleQMLearning W"D"M
;H-R- tutorialNidQ7.I
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not u*date data' . ! mys+lNerrorBCCI
\
echo MU*dated data success%ully?nMI
mys+lNcloseBRconnCI
YG
I% you want to delete a record %rom any MySQL ta&le) then you can use SQL
command <-L-T- PRAM! :ou can use this command at mys+lG *rom*t as
well as in any scri*t li$e H!
Syntax'
Here is generic SQL syntax o% <-L-T- command to delete data %rom a MySQL
ta&le'
<-L-T- PRAM ta&leNname 0;H-R- >lause2
I% ;H-R- clause is not s*eci,ed) then all the records will &e deleted %rom
the given MySQL ta&le!
:ou can s*eci%y any condition using ;H-R- clause!
:ou can delete records in a single ta&le at a time!
The ;H-R- clause is very use%ul when you want to delete selected rows in a
ta&le!
<eleting <ata %rom >ommand rom*t'
This will use SQL <-L-T- command with ;H-R- clause to delete selected
data into MySQL ta&le tutorialsNt&l!
-xam*le'
Pollowing exam*le will delete a record into tutorialNt&l whose tutorialNid is 7!
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG <-L-T- PRAM tutorialsNt&l ;H-R- tutorialNidQ7I
Query AT) L row aUected B5!E7 secC
mys+lG
<eleting <ata Using H Scri*t'
:ou can use SQL <-L-T- command with or without ;H-R- >L"US- into H
%unction mys+lN+ueryBC! This %unction will execute SQL command in similar
way it is executed at mys+lG *rom*t!
-xam*le'
Try out the %ollowing exam*le to delete a record %rom tutorialNt&l whose
tutorialNid is 7!
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rs+l Q .<-L-T- PRAM tutorialsNt&l
;H-R- tutorialNidQ7.I
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not delete data' . ! mys+lNerrorBCCI
\
echo M<eleted data success%ully?nMI
mys+lNcloseBRconnCI
YG
;e have seen SQL S-L->T command to %etch data %rom MySQL ta&le! ;e can
also use a conditional clause called ;H-R- clause to select re+uired records!
" ;H-R- clause with e+uals sign BQC wor$s ,ne where we want to do an
exact match! Li$e i% MtutorialNauthor Q .SanFay.M! #ut there may &e a
re+uirement where we want to ,lter out all the results where tutorialNauthor
name should contain MFayM! This can &e handled using SQL LIT- clause along
with ;H-R- clause!
I% SQL LIT- clause is used along with _ characters) then it will wor$ li$e a
meta character BOC in UNIX while listing out all the ,les or directories at
command *rom*t!
;ithout a _ character) LIT- clause is very similar to e+uals sign along with
;H-R- clause!
Syntax'
Here is generic SQL syntax o% S-L->T command along with LIT- clause to
%etch data %rom MySQL ta&le'
S-L->T ,eldL) ,eldE)!!!,eldN ta&leNnameL) ta&leNnameE!!!
;H-R- ,eldL LIT- conditionL 0"N< 0AR22 ,ledE Q .somevalue.
:ou can s*eci%y any condition using ;H-R- clause!
:ou can use LIT- clause along with ;H-R- clause!
:ou can use LIT- clause in *lace o% e+uals sign!
;hen LIT- is used along with _ sign then it will wor$ li$e a meta character
search!
:ou can s*eci%y more than one conditions using "N< or AR o*erators!
" ;H-R-!!!LIT- clause can &e used along with <-L-T- or U<"T- SQL
command also to s*eci%y a condition!
Using LIT- clause at >ommand rom*t'
This will use SQL S-L->T command with ;H-R-!!!LIT- clause to %etch
selected data %rom MySQL ta&le tutorialsNt&l!
-xam*le'
Pollowing exam*le will return all the records %rom tutorialsNt&l ta&le %or which
author name ends with Fay'
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG S-L->T O %rom tutorialsNt&l
(G ;H-R- tutorialNauthor LIT- ._Fay.I
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
K tutorialNid K tutorialNtitle K tutorialNauthor K su&missionNdate K
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
K 7 K W"D" Tutorial K SanFay K E55](54(EL K
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
L rows in set B5!5L secC
mys+lG
Using LIT- clause inside H Scri*t'
:ou can use similar syntax o% ;H-R-!!!LIT- clause into H %unction
mys+lN+ueryBC! This %unction is used to execute SQL command and later
another H %unction mys+lN%etchNarrayBC can &e used to %etch all the
selected data i% ;H-R-!!!LIT- clause is used along with S-L->T command!
#ut i% ;H-R-!!!LIT- clause is &eing used with <-L-T- or U<"T- command)
then no %urther H %unction call is re+uired!
-xam*le'
Try out the %ollowing exam*le to return all the records %rom tutorialsNt&l ta&le
%or which author name contains Fay'
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rs+l Q .S-L->T tutorialNid) tutorialNtitle)
tutorialNauthor) su&missionNdate
PRAM tutorialsNt&l
;H-R- tutorialNauthor LIT- M_Fay_M.I
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not get data' . ! mys+lNerrorBCCI
\
whileBRrow Q mys+lN%etchNarrayBRretval) M:SQLN"SSA>CC
[
echo MTutorial I< '[Rrow0.tutorialNid.2\ X&rG M!
MTitle' [Rrow0.tutorialNtitle.2\ X&rG M!
M"uthor' [Rrow0.tutorialNauthor.2\ X&rG M!
MSu&mission <ate ' [Rrow0.su&missionNdate.2\ X&rG M!
M((((((((((((((((((((((((((((((((X&rGMI
\
echo MPetched data success%ully?nMI
mys+lNcloseBRconnCI
YG
;e have seen SQL S-L->T command to %etch data %rom MySQL ta&le! ;hen
you select rows) the MySQL server is %ree to return them in any order) unless
you instruct it otherwise &y saying how to sort the result! #ut you sort a result
set &y adding an AR<-R #: clause that names the column or columns you
want to sort &y!
Syntax'
Here is generic SQL syntax o% S-L->T command along with AR<-R #: clause
to sort data %rom MySQL ta&le'
S-L->T ,eldL) ,eldE)!!!,eldN ta&leNnameL) ta&leNnameE!!!
AR<-R #: ,eldL) 0,eldE!!!2 0"S> 0<-S>22
:ou can sort returned result on any ,eld *rovided that ,led is &eing listed
out!
:ou can sort result on more than one ,eld!
:ou can use $eyword "S> or <-S> to get result in ascending or descending
order! #y de%ault) it.s ascending order!
:ou can use ;H-R-!!!LIT- clause in usual way to *ut condition!
Using AR<-R #: clause at >ommand rom*t'
This will use SQL S-L->T command with AR<-R #: clause to %etch data %rom
MySQL ta&le tutorialsNt&l!
-xam*le'
Try out the %ollowing exam*le) which returns result in ascending order!
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG S-L->T O %rom tutorialsNt&l AR<-R #: tutorialNauthor "S>
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
K tutorialNid K tutorialNtitle K tutorialNauthor K su&missionNdate K
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
K E K Learn MySQL K "&dul S K E55](54(EV K
K L K Learn H K Wohn oul K E55](54(EV K
K 7 K W"D" Tutorial K SanFay K E55](54(59 K
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
7 rows in set B5!VE secC
mys+lG
Deri%y all the author names are listed out in ascending order!
Using AR<-R #: clause inside H Scri*t'
:ou can use similar syntax o% AR<-R #: clause into H %unction
mys+lN+ueryBC! This %unction is used to execute SQL command and later
another H %unction mys+lN%etchNarrayBC can &e used to %etch all the
selected data!
-xam*le'
Try out the %ollowing exam*le) which returns result in descending order o%
tutorial author!
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rs+l Q .S-L->T tutorialNid) tutorialNtitle)
tutorialNauthor) su&missionNdate
PRAM tutorialsNt&l
AR<-R #: tutorialNauthor <-S>.I
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not get data' . ! mys+lNerrorBCCI
\
whileBRrow Q mys+lN%etchNarrayBRretval) M:SQLN"SSA>CC
[
echo MTutorial I< '[Rrow0.tutorialNid.2\ X&rG M!
MTitle' [Rrow0.tutorialNtitle.2\ X&rG M!
M"uthor' [Rrow0.tutorialNauthor.2\ X&rG M!
MSu&mission <ate ' [Rrow0.su&missionNdate.2\ X&rG M!
M((((((((((((((((((((((((((((((((X&rGMI
\
echo MPetched data success%ully?nMI
mys+lNcloseBRconnCI
YG
Thus %ar) we have only &een getting data %rom one ta&le at a time! This is ,ne
%or sim*le ta$es) &ut in most real world MySQL usage) you will o%ten need to
get data %rom multi*le ta&les in a single +uery!
:ou can use multi*le ta&les in your single SQL +uery! The act o% Foining in
MySQL re%ers to smashing two or more ta&les into a single ta&le!
:ou can use WAINS in S-L->T) U<"T- and <-L-T- statements to Foin MySQL
ta&les! ;e will see an exam*le o% L-PT WAIN also which is diUerent %rom
sim*le MySQL WAIN!
Using Woins at >ommand rom*t'
Su**ose we have two ta&les tcountNt&l and tutorialsNt&l in TUTARI"LS! "
com*lete listing is given &elow'
-xam*le'
Try out the %ollowing exam*les'
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG S-L->T O PRAM tcountNt&lI
J(((((((((((((((((J((((((((((((((((J
K tutorialNauthor K tutorialNcount K
J(((((((((((((((((J((((((((((((((((J
K mahran K E5 K
K mahna= K NULL K
K Wen K NULL K
K @ill K E5 K
K Wohn oul K L K
K SanFay K L K
J(((((((((((((((((J((((((((((((((((J
9 rows in set B5!5L secC
mys+lG S-L->T O %rom tutorialsNt&lI
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
K tutorialNid K tutorialNtitle K tutorialNauthor K su&missionNdate K
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
K L K Learn H K Wohn oul K E55](54(EV K
K E K Learn MySQL K "&dul S K E55](54(EV K
K 7 K W"D" Tutorial K SanFay K E55](54(59 K
J(((((((((((((J((((((((((((((((J(((((((((((((((((J(((((((((((((((((J
7 rows in set B5!55 secC
mys+lG
Now we can write a SQL +uery to Foin these two ta&les! This +uery will select
all the authors %rom ta&le tutorialsNt&l and will *ic$u* corres*onding num&er
o% tutorials %romtcountNt&l!
mys+lG S-L->T a!tutorialNid) a!tutorialNauthor) &!tutorialNcount
(G PRAM tutorialsNt&l a) tcountNt&l &
(G ;H-R- a!tutorialNauthor Q &!tutorialNauthorI
J(((((((((((((J(((((((((((((((((J((((((((((((((((J
K tutorialNid K tutorialNauthor K tutorialNcount K
J(((((((((((((J(((((((((((((((((J((((((((((((((((J
K L K Wohn oul K L K
K 7 K SanFay K L K
J(((((((((((((J(((((((((((((((((J((((((((((((((((J
E rows in set B5!5L secC
mys+lG
Using Woins in H Scri*t'
:ou can use any o% the a&ove(mentioned SQL +uery in H scri*t! :ou only
need to *ass SQL +uery into H %unction mys+lN+ueryBC and then you will
%etch results in usual way!
-xam*le'
Try out the %ollowing exam*le'
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rs+l Q .S-L->T a!tutorialNid) a!tutorialNauthor) &!tutorialNcount
PRAM tutorialsNt&l a) tcountNt&l &
;H-R- a!tutorialNauthor Q &!tutorialNauthor.I
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not get data' . ! mys+lNerrorBCCI
\
whileBRrow Q mys+lN%etchNarrayBRretval) M:SQLN"SSA>CC
[
echo M"uthor'[Rrow0.tutorialNauthor.2\ X&rG M!
M>ount' [Rrow0.tutorialNcount.2\ X&rG M!
MTutorial I<' [Rrow0.tutorialNid.2\ X&rG M!
M((((((((((((((((((((((((((((((((X&rGMI
\
echo MPetched data success%ully?nMI
mys+lNcloseBRconnCI
YG
MySQL L-PT WAIN'
" MySQL le%t Foin is diUerent %rom a sim*le Foin! " MySQL L-PT WAIN gives
extra consideration to the ta&le that is on the le%t!
I% I do a L-PT WAIN) I get all the records that match in the same way and IN
"<<ITIAN I get an extra record %or each unmatched record in the le%t ta&le o%
the Foin ( thus ensuring Bin my exam*leC that every "UTHAR gets a mention'
-xam*le'
Try out the %ollowing exam*le to understand L-PT WAIN'
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG S-L->T a!tutorialNid) a!tutorialNauthor) &!tutorialNcount
(G PRAM tutorialsNt&l a L-PT WAIN tcountNt&l &
(G AN a!tutorialNauthor Q &!tutorialNauthorI
J(((((((((((((J(((((((((((((((((J((((((((((((((((J
K tutorialNid K tutorialNauthor K tutorialNcount K
J(((((((((((((J(((((((((((((((((J((((((((((((((((J
K L K Wohn oul K L K
K E K "&dul S K NULL K
K 7 K SanFay K L K
J(((((((((((((J(((((((((((((((((J((((((((((((((((J
7 rows in set B5!5E secC
:ou would need to do more *ractice to &ecome %amiliar with WAINS! This is a
&it com*lex conce*t in MySQL/SQL and will &ecome more clear while doing
real exam*les!
;e have seen SQL S-L->T command along with ;H-R- clause to %etch data
%rom MySQL ta&le) &ut when we try to give a condition) which com*are ,eld
or column value to NULL) it does not wor$ *ro*erly!
To handle such situation MySQL *rovides three o*erators
IS NULL' o*erator returns true i% column value is NULL!
IS NAT NULL' o*erator returns true i% column value is not NULL!
XQG' o*erator com*ares values) which Bunli$e the Q o*eratorC is true even
%or two NULL values!
>onditions involving NULL are s*ecial! :ou cannot use Q NULL or ZQ NULL to
loo$ %or NULL values in columns! Such com*arisons always %ail &ecause it.s
im*ossi&le to tell whether or not they are true! -ven NULL Q NULL %ails!
To loo$ %or columns that are or are not NULL) use IS NULL or IS NAT NULL!
Using NULL values at >ommand rom*t'
Su**ose a ta&le tcountNt&l in TUTARI"LS data&ase and it contains two
columns tutorialNauthor and tutorialNcount) where a NULL tutorialNcount
indicates that the value is un$nown'
-xam*le'
Try out the %ollowing exam*les'
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG create ta&le tcountNt&l
(G B
(G tutorialNauthor varcharBV5C NAT NULL)
(G tutorialNcount INT
(G CI
Query AT) 5 rows aUected B5!54 secC
mys+lG INS-RT INTA tcountNt&l
(G BtutorialNauthor) tutorialNcountC values B.mahran.) E5CI
mys+lG INS-RT INTA tcountNt&l
(G BtutorialNauthor) tutorialNcountC values B.mahna=.) NULLCI
mys+lG INS-RT INTA tcountNt&l
(G BtutorialNauthor) tutorialNcountC values B.Wen.) NULLCI
mys+lG INS-RT INTA tcountNt&l
(G BtutorialNauthor) tutorialNcountC values B.@ill.) E5CI
mys+lG S-L->T O %rom tcountNt&lI
J(((((((((((((((((J((((((((((((((((J
K tutorialNauthor K tutorialNcount K
J(((((((((((((((((J((((((((((((((((J
K mahran K E5 K
K mahna= K NULL K
K Wen K NULL K
K @ill K E5 K
J(((((((((((((((((J((((((((((((((((J
V rows in set B5!55 secC
mys+lG
:ou can see that Q and ZQ do not wor$ with NULL values as %ollows'
mys+lG S-L->T O PRAM tcountNt&l ;H-R- tutorialNcount Q NULLI
-m*ty set B5!55 secC
mys+lG S-L->T O PRAM tcountNt&l ;H-R- tutorialNcount ZQ NULLI
-m*ty set B5!5L secC
To ,nd records where the tutorialNcount column is or is not NULL) the +ueries
should &e written li$e this'
mys+lG S-L->T O PRAM tcountNt&l
(G ;H-R- tutorialNcount IS NULLI
J(((((((((((((((((J((((((((((((((((J
K tutorialNauthor K tutorialNcount K
J(((((((((((((((((J((((((((((((((((J
K mahna= K NULL K
K Wen K NULL K
J(((((((((((((((((J((((((((((((((((J
E rows in set B5!55 secC
mys+lG S-L->T O %rom tcountNt&l
(G ;H-R- tutorialNcount IS NAT NULLI
J(((((((((((((((((J((((((((((((((((J
K tutorialNauthor K tutorialNcount K
J(((((((((((((((((J((((((((((((((((J
K mahran K E5 K
K @ill K E5 K
J(((((((((((((((((J((((((((((((((((J
E rows in set B5!55 secC
Handling NULL Dalues in H Scri*t'
:ou can use i%!!!else condition to *re*are a +uery &ased on NULL value!
-xam*le'
Pollowing exam*le ta$es tutorialNcount %rom outside and then com*ares it
with the value availa&le in the ta&le!
XY*h*
Rd&host Q .localhost'7579.I
Rd&user Q .root.I
Rd&*ass Q .root*assword.I
Rconn Q mys+lNconnectBRd&host) Rd&user) Rd&*assCI
i%BZ Rconn C
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
i%B issetBRtutorialNcount CC
[
Rs+l Q .S-L->T tutorialNauthor) tutorialNcount
PRAM tcountNt&l
;H-R- tutorialNcount Q RtutorialNcount.I
\
else
[
Rs+l Q .S-L->T tutorialNauthor) tutorialNcount
PRAM tcountNt&l
;H-R- tutorialNcount IS RtutorialNcount.I
\
mys+lNselectNd&B.TUTARI"LS.CI
Rretval Q mys+lN+ueryB Rs+l) Rconn CI
i%BZ Rretval C
[
dieB.>ould not get data' . ! mys+lNerrorBCCI
\
whileBRrow Q mys+lN%etchNarrayBRretval) M:SQLN"SSA>CC
[
echo M"uthor'[Rrow0.tutorialNauthor.2\ X&rG M!
M>ount' [Rrow0.tutorialNcount.2\ X&rG M!
M((((((((((((((((((((((((((((((((X&rGMI
\
echo MPetched data success%ully?nMI
mys+lNcloseBRconnCI
YG
:ou have seen MySQL *attern matching with LIT- !!!_! MySQL su**orts
another ty*e o% *attern matching o*eration &ased on regular ex*ressions and
the R-@-X o*erator! I% you are aware o% H or -RL) then it.s very sim*le
%or you to understand &ecause this matching is very similar to those scri*ting
regular ex*ressions!
Pollowing is the ta&le o% *attern which can &e used along with R-@-X
o*erator!
attern ;hat the *attern matches
` #eginning o% string
R -nd o% string
! "ny single character
0!!!2 "ny character listed &etween the s+uare &rac$ets
0`!!!2 "ny character not listed &etween the s+uare &rac$ets
*LK*EK*7 "lternationI matches any o% the *atterns *L) *E) or *7
O aero or more instances o% *receding element
J Ane or more instances o% *receding element
[n\ n instances o% *receding element
[m)n\m through n instances o% *receding element
-xam*les'
Now &ased on a&ove ta&le) you can device various ty*e o% SQL +ueries to
meet your re+uirements! Here) I.m listing %ew %or your understanding!
>onsider we have a ta&le called *ersonNt&l and it.s having a ,eld called
name'
Query to ,nd all the names starting with .st.
mys+lG S-L->T name PRAM *ersonNt&l ;H-R- name R-@-X .`st.I
Query to ,nd all the names ending with .o$.
mys+lG S-L->T name PRAM *ersonNt&l ;H-R- name R-@-X .o$R.I
Query to ,nd all the names) which contain .mar.
mys+lG S-L->T name PRAM *ersonNt&l ;H-R- name R-@-X .mar.I
Query to ,nd all the names starting with a vowel and ending with .o$.
mys+lG S-L->T name PRAM *ersonNt&l ;H-R- name R-@-X .`0aeiou2Ko$R.I
" transaction is a se+uential grou* o% data&ase mani*ulation o*erations)
which is *er%ormed as i% it were one single wor$ unit! In other words) a
transaction will never &e com*lete unless each individual o*eration within the
grou* is success%ul! I% any o*eration within the transaction %ails) the entire
transaction will %ail!
ractically) you will clu& many SQL +ueries into a grou* and you will execute
all o% them together as *art o% a transaction!
ro*erties o% Transactions'
Transactions have the %ollowing %our standard *ro*erties) usually re%erred to
&y the acronym ">I<'
"tomicity' ensures that all o*erations within the wor$ unit are com*leted
success%ullyI otherwise) the transaction is a&orted at the *oint o% %ailure and
*revious o*erations are rolled &ac$ to their %ormer state!
>onsistency' ensures that the data&ase *ro*erly changes states u*on a
success%ully committed transaction!
Isolation' ena&les transactions to o*erate inde*endently on and
trans*arent to each other!
<ura&ility' ensures that the result or eUect o% a committed transaction
*ersists in case o% a system %ailure!
In MySQL) transactions &egin with the statement #-@IN ;ART and end with
either a >AMMIT or a RALL#">T statement! The SQL commands &etween the
&eginning and ending statements %orm the &ul$ o% the transaction!
>AMMIT and RALL#">T'
These two $eywords >ommit and Roll&ac$ are mainly used %or MySQL
Transactions!
;hen a success%ul transaction is com*leted) the >AMMIT command should
&e issued so that the changes to all involved ta&les will ta$e eUect!
I% a %ailure occurs) a RALL#">T command should &e issued to return every
ta&le re%erenced in the transaction to its *revious state!
:ou can control the &ehavior o% a transaction &y setting session varia&le
called "UTA>AMMIT! I% "UTA>AMMIT is set to L Bthe de%aultC) then each SQL
statement Bwithin a transaction or notC is considered a com*lete transaction
and committed &y de%ault when it ,nishes! ;hen "UTA>AMMIT is set to 5) &y
issuing the S-T "UTA>AMMITQ5 command) the su&se+uent series o%
statements acts li$e a transaction and no activities are committed until an
ex*licit >AMMIT statement is issued!
:ou can execute these SQL commands in H &y using mys+lN+ueryBC
%unction!
@eneric -xam*le on Transaction
This se+uence o% events is inde*endent o% the *rogramming language usedI
the logical *ath can &e created in whichever language you use to create your
a**lication!
:ou can execute these SQL commands in H &y using mys+lN+ueryBC
%unction!
#egin transaction &y issuing SQL command #-@IN ;ART!
Issue one or more SQL commands li$e S-L->T) INS-RT) U<"T- or <-L-T-!
>hec$ i% there is no error and everything is according to your re+uirement!
I% there is any error) then issue RALL#">T command) otherwise issue a
>AMMIT command!
Transaction(Sa%e Ta&le Ty*es in MySQL'
:ou can not use transactions directly) you can &ut they would not &e sa%e and
guaranteed! I% you *lan to use transactions in your MySQL *rogramming) then
you need to create your ta&les in a s*ecial way! There are many ty*es o%
ta&les) which su**ort transactions &ut most *o*ular one is Inno<#!
Su**ort %or Inno<# ta&les re+uires a s*eci,c com*ilation *arameter when
com*iling MySQL %rom source! I% your MySQL version does not have Inno<#
su**ort) as$ your Internet Service rovider to &uild a version o% MySQL with
su**ort %or Inno<# ta&le ty*es or download and install the MySQL(Max &inary
distri&ution %or ;indows or Linux/UNIX and wor$ with the ta&le ty*e in a
develo*ment environment!
I% your MySQL installation su**orts Inno<# ta&les) sim*ly add a T:-QInno<#
de,nition to the ta&le creation statement! Por exam*le) the %ollowing code
creates an Inno<# ta&le called tcountNt&l'
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG create ta&le tcountNt&l
(G B
(G tutorialNauthor varcharBV5C NAT NULL)
(G tutorialNcount INT
(G C T:-QInno<#I
Query AT) 5 rows aUected B5!54 secC
>hec$ the %ollowing lin$ to $now more a&out' Inno<#
:ou can use other ta&le ty*es li$e @-MINI or #<#) &ut it de*ends on your
installation i% it su**orts these two ty*es!
MySQL "LT-R command is very use%ul when you want to change a name o%
your ta&le) any ta&le ,eld or i% you want to add or delete an existing column
in a ta&le!
Let.s &egin with creation o% a ta&le called testalterNt&l!
root1host3 mys+l (u root (* *asswordI
-nter *assword'OOOOOOO
mys+lG use TUTARI"LSI
<ata&ase changed
mys+lG create ta&le testalterNt&l
(G B
(G i INT)
(G c >H"RBLC
(G CI
Query AT) 5 rows aUected B5!54 secC
mys+lG SHA; >ALUMNS PRAM testalterNt&lI
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
K Pield K Ty*e K Null K Tey K <e%ault K -xtra K
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
K i K intBLLC K :-S K K NULL K K
K c K charBLC K :-S K K NULL K K
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
E rows in set B5!55 secC
<ro**ing) "dding or Re*ositioning a >olumn'
Su**ose you want to dro* an existing column i %rom a&ove MySQL ta&le then
you will use <RA clause along with "LT-R command as %ollows'
mys+lG "LT-R T"#L- testalterNt&l <RA iI
" <RA will not wor$ i% the column is the only one le%t in the ta&le!
To add a column) use "<< and s*eci%y the column de,nition! The %ollowing
statement restores the i column to testalterNt&l'
mys+lG "LT-R T"#L- testalterNt&l "<< i INTI
"%ter issuing this statement) testalter will contain the same two columns that
it had when you ,rst created the ta&le) &ut will not have +uite the same
structure! That.s &ecause new columns are added to the end o% the ta&le &y
de%ault! So even though i originally was the ,rst column in myt&l) now it is the
last one!
mys+lG SHA; >ALUMNS PRAM testalterNt&lI
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
K Pield K Ty*e K Null K Tey K <e%ault K -xtra K
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
K c K charBLC K :-S K K NULL K K
K i K intBLLC K :-S K K NULL K K
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
E rows in set B5!55 secC
To indicate that you want a column at a s*eci,c *osition within the ta&le)
either use PIRST to ma$e it the ,rst column or "PT-R colNname to indicate
that the new column should &e *laced a%ter colNname! Try the %ollowing "LT-R
T"#L- statements) using SHA; >ALUMNS a%ter each one to see what eUect
each one has'
"LT-R T"#L- testalterNt&l <RA iI
"LT-R T"#L- testalterNt&l "<< i INT PIRSTI
"LT-R T"#L- testalterNt&l <RA iI
"LT-R T"#L- testalterNt&l "<< i INT "PT-R cI
The PIRST and "PT-R s*eci,ers wor$ only with the "<< clause! This means
that i% you want to re*osition an existing column within a ta&le) you ,rst must
<RA it and then "<< it at the new *osition!
>hanging a >olumn <e,nition or Name'
To change a column.s de,nition) use MA<IP: or >H"N@- clause along with
"LT-R command! Por exam*le) to change column c %rom >H"RBLC to
>H"RBL5C) do this'
mys+lG "LT-R T"#L- testalterNt&l MA<IP: c >H"RBL5CI
;ith >H"N@-) the syntax is a &it diUerent! "%ter the >H"N@- $eyword) you
name the column you want to change) then s*eci%y the new de,nition) which
includes the new name! Try out the %ollowing exam*le'
mys+lG "LT-R T"#L- testalterNt&l >H"N@- i F #I@INTI
I% you now use >H"N@- to convert F %rom #I@INT &ac$ to INT without
changing the column name) the statement will &e as ex*ected'
mys+lG "LT-R T"#L- testalterNt&l >H"N@- F F INTI
The -Uect o% "LT-R T"#L- on Null and <e%ault Dalue "ttri&utes'
;hen you MA<IP: or >H"N@- a column) you can also s*eci%y whether or not
the column can contain NULL values and what its de%ault value is! In %act) i%
you don.t do this) MySQL automatically assigns values %or these attri&utes!
Here is the exam*le) where NAT NULL column will have value L55 &y de%ault!
mys+lG "LT-R T"#L- testalterNt&l
(G MA<IP: F #I@INT NAT NULL <-P"ULT L55I
I% you don.t use a&ove command) then MySQL will ,ll u* NULL values in all
the columns!
>hanging a >olumn.s <e%ault Dalue'
:ou can change a de%ault value %or any column using "LT-R command! Try out
the %ollowing exam*le!
mys+lG "LT-R T"#L- testalterNt&l "LT-R i S-T <-P"ULT L555I
mys+lG SHA; >ALUMNS PRAM testalterNt&lI
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
K Pield K Ty*e K Null K Tey K <e%ault K -xtra K
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
K c K charBLC K :-S K K NULL K K
K i K intBLLC K :-S K K L555 K K
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
E rows in set B5!55 secC
:ou can remove de%ault constraint %rom any column &y using <RA clause
along with "LT-R command!
mys+lG "LT-R T"#L- testalterNt&l "LT-R i <RA <-P"ULTI
mys+lG SHA; >ALUMNS PRAM testalterNt&lI
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
K Pield K Ty*e K Null K Tey K <e%ault K -xtra K
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
K c K charBLC K :-S K K NULL K K
K i K intBLLC K :-S K K NULL K K
J(((((((J(((((((((J((((((J(((((J(((((((((J(((((((J
E rows in set B5!55 secC
>hanging a Ta&le Ty*e'
:ou can use a ta&le ty*e &y using T:- clause along with "LT-R command!
Try out the %ollowing exam*le to change testalterNt&l to M:IS"M ta&le ty*e!
To ,nd out the current ty*e o% a ta&le) use the SHA; T"#L- ST"TUS
statement!
mys+lG "LT-R T"#L- testalterNt&l T:- Q M:IS"MI
mys+lG SHA; T"#L- ST"TUS LIT- .testalterNt&l.?@
OOOOOOOOOOOOOOOOOOOOOOOOOOO L! row OOOOOOOOOOOOOOOO
Name' testalterNt&l
Ty*e' MyIS"M
RowN%ormat' Pixed
Rows' 5
"vgNrowNlength' 5
<ataNlength' 5
MaxNdataNlength' E4]96857]]4
IndexNlength' L5EV
<ataN%ree' 5
"utoNincrement' NULL
>reateNtime' E55](59(57 58'5V'79
U*dateNtime' E55](59(57 58'5V'79
>hec$Ntime' NULL
>reateNo*tions'
>omment'
L row in set B5!55 secC
Renaming a Ta&le'
To rename a ta&le) use the R-N"M- o*tion o% the "LT-R T"#L- statement! Try
out the %ollowing exam*le to rename testalterNt&l to alterNt&l!
mys+lG "LT-R T"#L- testalterNt&l R-N"M- TA alterNt&lI
:ou can use "LT-R command to create and dro* IN<-X on a MySQL ,le! ;e
will see this %eature in next cha*ter!
" data&ase index is a data structure that im*roves the s*eed o% o*erations in
a ta&le! Indexes can &e created using one or more columns) *roviding the
&asis %or &oth ra*id random loo$u*s and e/cient ordering o% access to
records!
;hile creating index) it should &e considered that what are the columns
which will &e used to ma$e SQL +ueries and create one or more indexes on
those columns!
ractically) indexes are also ty*e o% ta&les) which $ee* *rimary $ey or index
,eld and a *ointer to each record into the actual ta&le!
The users cannot see the indexes) they are Fust used to s*eed u* +ueries and
will &e used &y <ata&ase Search -ngine to locate records very %ast!
INS-RT and U<"T- statements ta$es more time on ta&les having indexes
where as S-L->T statements &ecome %ast on those ta&les! The reason is that
while doing insert or u*date) data&ase need to insert or u*date index values
as well!
Sim*le and Uni+ue Index'
:ou can create a uni+ue index on a ta&le! " uni+ue index means that two
rows cannot have the same index value! Here is the syntax to create an Index
on a ta&le
>R-"T- UNIQU- IN<-X indexNname
AN ta&leNname B columnL) columnE)!!!CI
:ou can use one or more columns to create an index! Por exam*le) we can
create an index on tutorialsNt&l using tutorialNauthor!
>R-"T- UNIQU- IN<-X "UTHARNIN<-X
AN tutorialsNt&l BtutorialNauthorC
:ou can create a sim*le index on a ta&le! Wust omit UNIQU- $eyword %rom the
+uery to create sim*le index! Sim*le index allows du*licate values in a ta&le!
I% you want to index the values in a column in descending order) you can add
the reserved word <-S> a%ter the column name!
mys+lG >R-"T- UNIQU- IN<-X "UTHARNIN<-X
AN tutorialsNt&l BtutorialNauthor <-S>C
"LT-R command to add and dro* IN<-X'
There are %our ty*es o% statements %or adding indexes to a ta&le'
"LT-R T"#L- t&lNname "<< RIM"R: T-: BcolumnNlistC' This statement
adds a RIM"R: T-:) which means that indexed values must &e uni+ue and
cannot &e NULL!
"LT-R T"#L- t&lNname "<< UNIQU- indexNname BcolumnNlistC' This
statement creates an index %or which values must &e uni+ue Bwith the
exce*tion o% NULL values) which may a**ear multi*le timesC!
"LT-R T"#L- t&lNname "<< IN<-X indexNname BcolumnNlistC' This adds an
ordinary index in which any value may a**ear more than once!
"LT-R T"#L- t&lNname "<< PULLT-XT indexNname BcolumnNlistC' This
creates a s*ecial PULLT-XT index that is used %or text(searching *ur*oses!
Here is the exam*le to add index in an existing ta&le!
mys+lG "LT-R T"#L- testalterNt&l "<< IN<-X BcCI
:ou can dro* any IN<-X &y using <RA clause along with "LT-R command!
Try out the %ollowing exam*le to dro* a&ove(created index!
mys+lG "LT-R T"#L- testalterNt&l <RA IN<-X BcCI
:ou can dro* any IN<-X &y using <RA clause along with "LT-R command!
Try out the %ollowing exam*le to dro* a&ove(created index!
"LT-R >ommand to add and dro* RIM"R: T-:'
:ou can add *rimary $ey as well in the same way! #ut ma$e sure rimary Tey
wor$s on columns) which are NAT NULL!
Here is the exam*le to add *rimary $ey in an existing ta&le! This will ma$e a
column NAT NULL ,rst and then add it as a *rimary $ey!
mys+lG "LT-R T"#L- testalterNt&l MA<IP: i INT NAT NULLI
mys+lG "LT-R T"#L- testalterNt&l "<< RIM"R: T-: BiCI
:ou can use "LT-R command to dro* a *rimary $ey as %ollows'
mys+lG "LT-R T"#L- testalterNt&l <RA RIM"R: T-:I
To dro* an index that is not a RIM"R: T-:) you must s*eci%y the index name!
<is*laying IN<-X In%ormation'
:ou can use SHA; IN<-X command to list out all the indexes associated with
a ta&le! Dertical(%ormat out*ut Bs*eci,ed &y ?@C o%ten is use%ul with this
statement) to avoid long line wra*around'
Try out the %ollowing exam*le'
mys+lG SHA; IN<-X PRAM ta&leNname?@
!!!!!!!!
The tem*orary ta&les could &e very use%ul in some cases to $ee* tem*orary
data! The most im*ortant thing that should &e $nown %or tem*orary ta&les is
that they will &e deleted when the current client session terminates!
Tem*orary ta&les were added in MySQL version 7!E7! I% you use an older
version o% MySQL than 7!E7) you can.t use tem*orary ta&les) &ut you can use
hea* ta&les!
"s stated earlier) tem*orary ta&les will only last as long as the session is
alive! I% you run the code in a H scri*t) the tem*orary ta&le will &e
destroyed automatically when the scri*t ,nishes executing! I% you are
connected to the MySQL data&ase server through the MySQL client *rogram)
then the tem*orary ta&le will exist until you close the client or manually
destroy the ta&le!
-xam*le'
Here is an exam*le showing you usage o% tem*orary ta&le! Same code can &e
used in H scri*ts using mys+lN+ueryBC %unction!
mys+lG >R-"T- T-MAR"R: T"#L- SalesSummary B
(G *roductNname D"R>H"RB45C NAT NULL
(G ) totalNsales <->IM"LBLE)EC NAT NULL <-P"ULT 5!55
(G ) avgNunitN*rice <->IM"LB])EC NAT NULL <-P"ULT 5!55
(G ) totalNunitsNsold INT UNSI@N-< NAT NULL <-P"ULT 5
CI
Query AT) 5 rows aUected B5!55 secC
mys+lG INS-RT INTA SalesSummary
(G B*roductNname) totalNsales) avgNunitN*rice) totalNunitsNsoldC
(G D"LU-S
(G B.cucum&er.) L55!E4) 65) ECI
mys+lG S-L->T O PRAM SalesSummaryI
J((((((((((((((J(((((((((((((J((((((((((((((((J((((((((((((((((((J
K *roductNname K totalNsales K avgNunitN*rice K totalNunitsNsold K
J((((((((((((((J(((((((((((((J((((((((((((((((J((((((((((((((((((J
K cucum&er K L55!E4 K 65!55 K E K
J((((((((((((((J(((((((((((((J((((((((((((((((J((((((((((((((((((J
L row in set B5!55 secC
;hen you issue a SHA; T"#L-S command) then your tem*orary ta&le would
not &e listed out in the list! Now) i% you will log out o% the MySQL session and
then you will issue a S-L->T command) then you will ,nd no data availa&le in
the data&ase! -ven your tem*orary ta&le would also not exist!
<ro**ing Tem*orary Ta&les'
#y de%ault) all the tem*orary ta&les are deleted &y MySQL when your
data&ase connection gets terminated! Still i% you want to delete them in
&etween) then you do so &y issuing <RA T"#L- command!
Pollowing is the exam*le on dro**ing a tem*orary ta&le'
mys+lG >R-"T- T-MAR"R: T"#L- SalesSummary B
(G *roductNname D"R>H"RB45C NAT NULL
(G ) totalNsales <->IM"LBLE)EC NAT NULL <-P"ULT 5!55
(G ) avgNunitN*rice <->IM"LB])EC NAT NULL <-P"ULT 5!55
(G ) totalNunitsNsold INT UNSI@N-< NAT NULL <-P"ULT 5
CI
Query AT) 5 rows aUected B5!55 secC
mys+lG INS-RT INTA SalesSummary
(G B*roductNname) totalNsales) avgNunitN*rice) totalNunitsNsoldC
(G D"LU-S
(G B.cucum&er.) L55!E4) 65) ECI
mys+lG S-L->T O PRAM SalesSummaryI
J((((((((((((((J(((((((((((((J((((((((((((((((J((((((((((((((((((J
K *roductNname K totalNsales K avgNunitN*rice K totalNunitsNsold K
J((((((((((((((J(((((((((((((J((((((((((((((((J((((((((((((((((((J
K cucum&er K L55!E4 K 65!55 K E K
J((((((((((((((J(((((((((((((J((((((((((((((((J((((((((((((((((((J
L row in set B5!55 secC
mys+lG <RA T"#L- SalesSummaryI
mys+lG S-L->T O PRAM SalesSummaryI
-RRAR LLV9' Ta&le .TUTARI"LS!SalesSummary. doesn.t exist
There may &e a situation when you need an exact co*y o% a ta&le and
>R-"T- T"#L- !!! S-L->T doesn.t suit your *ur*oses &ecause the co*y must
include the same indexes) de%ault values) and so %orth!
:ou can handle this situation &y %ollowing ste*s'
Use SHA; >R-"T- T"#L- to get a >R-"T- T"#L- statement that s*eci,es
the source ta&le.s structure) indexes and all!
Modi%y the statement to change the ta&le name to that o% the clone ta&le
and execute the statement! This way) you will have exact clone ta&le!
A*tionally) i% you need the ta&le contents co*ied as well) issue an INS-RT
INTA !!! S-L->T statement) too!
-xam*le'
Try out the %ollowing exam*le to create a clone ta&le %or tutorialsNt&l!
Ste* L'
@et com*lete structure a&out ta&le!
mys+lG SHA; >R-"T- T"#L- tutorialsNt&l ?@I
OOOOOOOOOOOOOOOOOOOOOOOOOOO L! row OOOOOOOOOOOOOOOOOOOOOOOOOOO
Ta&le' tutorialsNt&l
>reate Ta&le' >R-"T- T"#L- btutorialsNt&lb B
btutorialNidb intBLLC NAT NULL autoNincrement)
btutorialNtitleb varcharBL55C NAT NULL de%ault ..)
btutorialNauthorb varcharBV5C NAT NULL de%ault ..)
bsu&missionNdateb date de%ault NULL)
RIM"R: T-: BbtutorialNidbC)
UNIQU- T-: b"UTHARNIN<-Xb BbtutorialNauthorbC
C T:-QMyIS"M
L row in set B5!55 secC
-RRAR'
No +uery s*eci,ed
Ste* E'
Rename this ta&le and create another ta&le!
mys+lG >R-"T- T"#L- bcloneNt&lb B
(G btutorialNidb intBLLC NAT NULL autoNincrement)
(G btutorialNtitleb varcharBL55C NAT NULL de%ault ..)
(G btutorialNauthorb varcharBV5C NAT NULL de%ault ..)
(G bsu&missionNdateb date de%ault NULL)
(G RIM"R: T-: BbtutorialNidbC)
(G UNIQU- T-: b"UTHARNIN<-Xb BbtutorialNauthorbC
(G C T:-QMyIS"MI
Query AT) 5 rows aUected BL!85 secC
Ste* 7'
"%ter executing ste* E) you will create a clone ta&le in your data&ase! I% you
want to co*y data %rom old ta&le then you can do it &y using INS-RT INTA!!!
S-L->T statement!
mys+lG INS-RT INTA cloneNt&l BtutorialNid)
(G tutorialNtitle)
(G tutorialNauthor)
(G su&missionNdateC
(G S-L->T tutorialNid)tutorialNtitle)
(G tutorialNauthor)su&missionNdate)
(G PRAM tutorialsNt&lI
Query AT) 7 rows aUected B5!5] secC
Records' 7 <u*licates' 5 ;arnings' 5
Pinally) you will have exact clone ta&le as you wanted to have!
There are three in%ormations) which you would li$e to have %rom MySQL!
In%ormation a&out the result o% +ueries' This includes num&er o% records
aUected &y any S-L->T) U<"T- or <-L-T- statement!
In%ormation a&out ta&les and data&ases' This includes in%ormation
*ertaining to the structure o% ta&les and data&ases!
In%ormation a&out the MySQL server' This includes current status o%
data&ase server) version num&er etc!
It.s very easy to get all these in%ormation at mys+l *rom*t) &ut while using
-RL or H "Is) then we need to call various "Is ex*licitely to o&tain all
these in%ormation! Pollowing section will show you how to o&tain this
in%ormation!
A&taining the Num&er o% Rows "Uected &y a Query'
-RL -xam*le'
In <#I scri*ts) the aUected(rows count is returned &y doB C or &y executeB C)
de*ending on how you execute the +uery'
3 Method L
3 execute R+uery using doB C
my Rcount Q Rd&h(Gdo BR+ueryCI
3 re*ort 5 rows i% an error occurred
*rint% M_d rows were aUected?nM) Bde,ned BRcountC Y Rcount ' 5CI
3 Method E
3 execute +uery using *re*areB C *lus executeB C
my Rsth Q Rd&h(G*re*are BR+ueryCI
my Rcount Q Rsth(Gexecute B CI
*rint% M_d rows were aUected?nM) Bde,ned BRcountC Y Rcount ' 5CI
H -xam*le'
In H) invo$e the mys+lNaUectedNrowsB C %unction to ,nd out how many rows
a +uery changed'
RresultNid Q mys+lN+uery BR+uery) RconnNidCI
3 re*ort 5 rows i% the +uery %ailed
Rcount Q BRresultNid Y mys+lNaUectedNrows BRconnNidC ' 5CI
*rint BMRcount rows were aUected?nMCI
Listing Ta&les and <ata&ases'
This is very easy to list down all the data&ases and ta&les availa&le with
data&ase server! :our result may &e null i% you don.t have su/cient *rivilege!
"*art %rom the method I have mentioned &elow) you can use SHA; T"#L-S
or SHA; <"T"#"S-S +ueries to get list o% ta&les or data&ases either in H
or in -RL!
-RL -xam*le'
3 @et all the ta&les availa&le in current data&ase!
my 1ta&les Q Rd&h(Gta&les B CI
%oreach Rta&le B1ta&les C[
*rint MTa&le Name Rta&le?nMI
\
H -xam*le'
XY*h*
Rcon Q mys+lNconnectBMlocalhostM) MuseridM) M*asswordMCI
i% BZRconC
[
dieB.>ould not connect' . ! mys+lNerrorBCCI
\
Rd&Nlist Q mys+lNlistNd&sBRconCI
while BRd& Q mys+lN%etchNo&FectBRd&NlistCC
[
echo Rd&(G<ata&ase ! MX&r /GMI
\
mys+lNcloseBRconCI
YG
@etting Server Metadata'
There are %ollowing commands in MySQL which can &e executed either at
mys+l *rom*t or using any scri*t li$e H to get various im*ortant
in%ormations a&out data&ase server!
>ommand <escri*tion
S-L->T D-RSIANB C Server version string
S-L->T <"T"#"S-B C >urrent data&ase name Bem*ty i% noneC
S-L->T US-RB C >urrent username
SHA; ST"TUS Server status indicators
SHA; D"RI"#L-S Server con,guration varia&les
" se+uence is a set o% integers L) E) 7) !!! that are generated in order on
demand! Se+uences are %re+uently used in data&ases &ecause many
a**lications re+uire each row in a ta&le to contain a uni+ue value and
se+uences *rovide an easy way to generate them! This cha*ter descri&es
how to use se+uences in MySQL!
Using "UTANIN>R-M-NT column'
The sim*lest way in MySQL to use Se+uences is to de,ne a column as
"UTANIN>R-M-NT and leave rest o% the things to MySQL to ta$e care!
-xam*le'
Try out the %ollowing exam*le! This will create ta&le and a%ter that it will insert
%ew rows in this ta&le where it is not re+uired to give record I< &ecause it.s
auto incremented &y MySQL!
mys+lG >R-"T- T"#L- insect
(G B
(G id INT UNSI@N-< NAT NULL "UTANIN>R-M-NT)
(G RIM"R: T-: BidC)
(G name D"R>H"RB75C NAT NULL) 3 ty*e o% insect
(G date <"T- NAT NULL) 3 date collected
(G origin D"R>H"RB75C NAT NULL 3 where collected
CI
Query AT) 5 rows aUected B5!5E secC
mys+lG INS-RT INTA insect Bid)name)date)originC D"LU-S
(G BNULL).house^y.).E55L(56(L5.).$itchen.C)
(G BNULL).milli*ede.).E55L(56(L5.).driveway.C)
(G BNULL).grassho**er.).E55L(56(L5.).%ront yard.CI
Query AT) 7 rows aUected B5!5E secC
Records' 7 <u*licates' 5 ;arnings' 5
mys+lG S-L->T O PRAM insect AR<-R #: idI
J((((J(((((((((((((J((((((((((((J((((((((((((J
K id K name K date K origin K
J((((J(((((((((((((J((((((((((((J((((((((((((J
K L K house^y K E55L(56(L5 K $itchen K
K E K milli*ede K E55L(56(L5 K driveway K
K 7 K grassho**er K E55L(56(L5 K %ront yard K
J((((J(((((((((((((J((((((((((((J((((((((((((J
7 rows in set B5!55 secC
A&tain "UTANIN>R-M-NT Dalues'
L"STNINS-RTNI<B C is a SQL %unction) so you can use it %rom within any client
that understands how to issue SQL statements! Atherwise) -RL and H
scri*ts *rovide exclusive %unctions to retrieve auto incremented value o% last
record!
-RL -xam*le'
Use the mys+lNinsertid attri&ute to o&tain the "UTANIN>R-M-NT value
generated &y a +uery! This attri&ute is accessed through either a data&ase
handle or a statement handle) de*ending on how you issue the +uery! The
%ollowing exam*le re%erences it through the data&ase handle'
Rd&h(Gdo BMINS-RT INTA insect Bname)date)originC
D"LU-SB.moth.).E55L(56(LV.).windowsill.CMCI
my Rse+ Q Rd&h(G[mys+lNinsertid\I
H -xam*le'
"%ter issuing a +uery that generates an "UTANIN>R-M-NT value) retrieve the
value &y calling mys+lNinsertNidB C'
mys+lN+uery BMINS-RT INTA insect Bname)date)originC
D"LU-SB.moth.).E55L(56(LV.).windowsill.CM) RconnNidCI
Rse+ Q mys+lNinsertNid BRconnNidCI
Renum&ering an -xisting Se+uence'
There may &e a case when you have deleted many records %rom a ta&le and
you want to rese+uence all the records! This can &e done &y using a sim*le
tric$ &ut you should &e very care%ul to do so i% your ta&le is having Foins with
other ta&le!
I% you determine that rese+uencing an "UTANIN>R-M-NT column is
unavoida&le) the way to do it is to dro* the column %rom the ta&le) then add it
again! The %ollowing exam*le shows how to renum&er the id values in the
insect ta&le using this techni+ue'
mys+lG "LT-R T"#L- insect <RA idI
mys+lG "LT-R T"#L- insect
(G "<< id INT UNSI@N-< NAT NULL "UTANIN>R-M-NT PIRST)
(G "<< RIM"R: T-: BidCI
Starting a Se+uence at a articular Dalue'
#y de%ault) MySQL will start se+uence %rom L &ut you can s*eci%y any other
num&er as well at the time o% ta&le creation! Pollowing is the exam*le where
MySQL will start se+uence %rom L55!
mys+lG >R-"T- T"#L- insect
(G B
(G id INT UNSI@N-< NAT NULL "UTANIN>R-M-NT Q L55)
(G RIM"R: T-: BidC)
(G name D"R>H"RB75C NAT NULL) 3 ty*e o% insect
(G date <"T- NAT NULL) 3 date collected
(G origin D"R>H"RB75C NAT NULL 3 where collected
CI
"lternatively) you can create the ta&le and then set the initial se+uence value
with "LT-R T"#L-!
mys+lG "LT-R T"#L- t "UTANIN>R-M-NT Q L55I
Ta&les or result sets sometimes contain du*licate records! Sometimes) it is
allowed &ut sometimes it is re+uired to sto* du*licate records! Sometimes) it
is re+uired to identi%y du*licate records and remove them %rom the ta&le! This
cha*ter will descri&e how to *revent du*licate records occurring in a ta&le
and how to remove already existing du*licate records!
reventing <u*licates %rom Accurring in a Ta&le'
:ou can use a RIM"R: T-: or UNIQU- Index on a ta&le with a**ro*riate
,elds to sto* du*licate records! Let.s ta$e one exam*le' The %ollowing ta&le
contains no such index or *rimary $ey) so it would allow du*licate records %or
,rstNname and lastNname!
>R-"T- T"#L- *ersonNt&l
B
,rstNname >H"RBE5C)
lastNname >H"RBE5C)
sex >H"RBL5C
CI
To *revent multi*le records with the same ,rst and last name values %rom
&eing created in this ta&le) add a RIM"R: T-: to its de,nition! ;hen you do
this) it.s also necessary to declare the indexed columns to &e NAT NULL)
&ecause a RIM"R: T-: does not allow NULL values'
>R-"T- T"#L- *ersonNt&l
B
,rstNname >H"RBE5C NAT NULL)
lastNname >H"RBE5C NAT NULL)
sex >H"RBL5C
RIM"R: T-: BlastNname) ,rstNnameC
CI
The *resence o% a uni+ue index in a ta&le normally causes an error to occur i%
you insert a record into the ta&le that du*licates an existing record in the
column or columns that de,ne the index!
Use INS-RT I@NAR- rather than INS-RT! I% a record doesn.t du*licate an
existing record) MySQL inserts it as usual! I% the record is a du*licate) the
I@NAR- $eyword tells MySQL to discard it silently without generating an error!
Pollowing exam*le does not error out and same time it will not insert
du*licate records!
mys+lG INS-RT I@NAR- INTA *ersonNt&l BlastNname) ,rstNnameC
(G D"LU-SB .Way.) .Thomas.CI
Query AT) L row aUected B5!55 secC
mys+lG INS-RT I@NAR- INTA *ersonNt&l BlastNname) ,rstNnameC
(G D"LU-SB .Way.) .Thomas.CI
Query AT) 5 rows aUected B5!55 secC
Use R-L">- rather than INS-RT! I% the record is new) it.s inserted Fust as with
INS-RT! I% it.s a du*licate) the new record re*laces the old one'
mys+lG R-L">- INTA *ersonNt&l BlastNname) ,rstNnameC
(G D"LU-SB ."Fay.) .Tumar.CI
Query AT) L row aUected B5!55 secC
mys+lG R-L">- INTA *ersonNt&l BlastNname) ,rstNnameC
(G D"LU-SB ."Fay.) .Tumar.CI
Query AT) E rows aUected B5!55 secC
INS-RT I@NAR- and R-L">- should &e chosen according to the du*licate(
handling &ehavior you want to eUect! INS-RT I@NAR- $ee*s the ,rst o% a set
o% du*licated records and discards the rest! R-L">- $ee*s the last o% a set o%
du*licates and erase out any earlier ones!
"nother way to en%orce uni+ueness is to add a UNIQU- index rather than a
RIM"R: T-: to a ta&le!
>R-"T- T"#L- *ersonNt&l
B
,rstNname >H"RBE5C NAT NULL)
lastNname >H"RBE5C NAT NULL)
sex >H"RBL5C
UNIQU- BlastNname) ,rstNnameC
CI
>ounting and Identi%ying <u*licates'
Pollowing is the +uery to count du*licate records with ,rstNname and
lastNname in a ta&le!
mys+lG S-L->T >AUNTBOC as re*etitions) lastNname) ,rstNname
(G PRAM *ersonNt&l
(G @RAU #: lastNname) ,rstNname
(G H"DIN@ re*etitions G LI
This +uery will return a list o% all the du*licate records in *ersonNt&l ta&le! In
general) to identi%y sets o% values that are du*licated) do the %ollowing'
<etermine which columns contain the values that may &e du*licated!
List those columns in the column selection list) along with >AUNTBOC!
List the columns in the @RAU #: clause as well!
"dd a H"DIN@ clause that eliminates uni+ue values &y re+uiring grou*
counts to &e greater than one!
-liminating <u*licates %rom a Query Result'
:ou can use <ISTIN>T along with S-L->T statement to ,nd out uni+ue records
availa&le in a ta&le!
mys+lG S-L->T <ISTIN>T lastNname) ,rstNname
(G PRAM *ersonNt&l
(G AR<-R #: lastNnameI
"n alternative to <ISTIN>T is to add a @RAU #: clause that names the
columns you.re selecting! This has the eUect o% removing du*licates and
selecting only the uni+ue com&inations o% values in the s*eci,ed columns'
mys+lG S-L->T lastNname) ,rstNname
(G PRAM *ersonNt&l
(G @RAU #: BlastNname) ,rstNnameCI
Removing <u*licates Using Ta&le Re*lacement'
I% you have du*licate records in a ta&le and you want to remove all the
du*licate records %rom that ta&le) then here is the *rocedure'
mys+lG >R-"T- T"#L- tm* S-L->T lastNname) ,rstNname) sex
(G PRAM *ersonNt&lI
(G @RAU #: BlastNname) ,rstNnameCI
mys+lG <RA T"#L- *ersonNt&lI
mys+lG "LT-R T"#L- tm* R-N"M- TA *ersonNt&lI
"n easy way o% removing du*licate records %rom a ta&le is to add an IN<-X or
RIM": T-: to that ta&le! -ven i% this ta&le is already availa&le) you can use
this techni+ue to remove du*licate records and you will &e sa%e in %uture as
well!
mys+lG "LT-R I@NAR- T"#L- *ersonNt&l
(G "<< RIM"R: T-: BlastNname) ,rstNnameCI
I% you ta$e user in*ut through a we&*age and insert it into a MySQL
data&ase) there.s a chance that you have le%t yoursel% wide o*en %or a
security issue $nown as SQL InFection! This lesson will teach you how to hel*
*revent this %rom ha**ening and hel* you secure your scri*ts and MySQL
statements!
InFection usually occurs when you as$ a user %or in*ut) li$e their name and
instead o% a name they give you a MySQL statement that you will
un$nowingly run on your data&ase!
Never trust user *rovided data) *rocess this data only a%ter validationI as a
rule) this is done &y *attern matching! In the exam*le &elow) the username is
restricted to al*hanumerical chars *lus underscore and to a length &etween 8
and E5 chars ( modi%y these rules as needed!
i% B*regNmatchBM/`?w[8)E5\R/M) RN@-T0.username.2) RmatchesCC
[
Rresult Q mys+lN+ueryBMS-L->T O PRAM users
;H-R- usernameQRmatches052MCI
\
else
[
echo Musername not acce*tedMI
\
To demonstrate the *ro&lem) consider this excer*t'
// su**osed in*ut
Rname Q MQadir.I <-L-T- PRAM usersIMI
mys+lN+ueryBMS-L->T O PRAM users ;H-R- nameQ.[Rname\.MCI
The %unction call is su**osed to retrieve a record %rom the users ta&le) where
the name column matches the name s*eci,ed &y the user! Under normal
circumstances) Rname would only contain al*hanumeric characters and
*erha*s s*aces) such as the string ilia! #ut here) &y a**ending an entirely
new +uery to Rname) the call to the data&ase turns into disaster' the inFected
<-L-T- +uery removes all records %rom users!
Portunately) i% you use MySQL) the mys+lN+ueryBC %unction does not *ermit
+uery stac$ing or executing multi*le +ueries in a single %unction call! I% you
try to stac$ +ueries) the call %ails!
However) other H data&ase extensions) such as SQLite and ostgreSQL)
ha**ily *er%orm stac$ed +ueries) executing all o% the +ueries *rovided in one
string and creating a serious security *ro&lem!
reventing SQL InFection'
:ou can handle all esca*e characters smartly in scri*ting languages li$e -RL
and H! The MySQL extension %or H *rovides the %unction
mys+lNrealNesca*eNstringBC to esca*e in*ut characters that are s*ecial to
MySQL!
i% BgetNmagicN+uotesNg*cBCC
[
Rname Q stri*slashesBRnameCI
\
Rname Q mys+lNrealNesca*eNstringBRnameCI
mys+lN+ueryBMS-L->T O PRAM users ;H-R- nameQ.[Rname\.MCI
The LIT- Quandary'
To address the LIT- +uandary) a custom esca*ing mechanism must convert
user(su**lied _ and N characters to literals! Use addcslashesBC) a %unction
that let.s you s*eci%y a character range to esca*e!
Rsu& Q addcslashesBmys+lNrealNesca*eNstringBM_somethingNMC) M_NMCI
// Rsu& QQ ?_something?N
mys+lN+ueryBMS-L->T O PRAM messages ;H-R- su&Fect LIT- .[Rsu&\_.MCI
The sim*lest way o% ex*orting a ta&le data into a text ,le is using
S-L->T!!!INTA AUTPIL- statement that ex*orts a +uery result directly into a
,le on the server host!
-x*orting <ata with the S-L->T !!! INTA AUTPIL- Statement'
The syntax %or this statement com&ines a regular S-L->T with INTA AUTPIL-
,lename at the end! The de%ault out*ut %ormat is the same as %or LA"< <"T")
so the %ollowing statement ex*orts the tutorialsNt&l ta&le into
/tm*/tutorials!txt as a ta&(delimited) line%eed(terminated ,le'
mys+lG S-L->T O PRAM tutorialsNt&l
(G INTA AUTPIL- ./tm*/tutorials!txt.I
:ou can change the out*ut %ormat using o*tions to indicate how to +uote and
delimit columns and records! To ex*ort the tutorialNt&l ta&le in >SD %ormat
with >RLP(terminated lines) use this statement'
mys+lG S-L->T O PRAM *asswd INTA AUTPIL- ./tm*/tutorials!txt.
(G PI-L<S T-RMIN"T-< #: .). -N>LAS-< #: .M.
(G LIN-S T-RMIN"T-< #: .?r?n.I
The S-L->T !!! INTA AUTPIL- has the %ollowing *ro*erties'
The out*ut ,le is created directly &y the MySQL server) so the ,lename
should indicate where you want the ,le to &e written on the server host!
There is no LA>"L version o% the statement analogous to the LA>"L version
o% LA"< <"T"!
:ou must have the MySQL PIL- *rivilege to execute the S-L->T !!! INTA
statement!
The out*ut ,le must not already exist! This *revents MySQL %rom
clo&&ering ,les that may &e im*ortant!
:ou should have a login account on the server host or some way to retrieve
the ,le %rom that host! Atherwise) S-L->T !!! INTA AUTPIL- li$ely will &e o% no
value to you!
Under UNIX) the ,le is created world reada&le and is owned &y the MySQL
server! This means that although you.ll &e a&le to read the ,le) you may not
&e a&le to delete it!
-x*orting Ta&les as Raw <ata'
The mys+ldum* *rogram is used to co*y or &ac$ u* ta&les and data&ases! It
can write ta&le out*ut either as a raw data,le or as a set o% INS-RT
statements that recreate the records in the ta&le!
To dum* a ta&le as a data,le) you must s*eci%y a ((ta& o*tion that indicates
the directory) where you want the MySQL server to write the ,le!
Por exam*le) to dum* the tutorialsNt&l ta&le %rom the TUTARI"LS data&ase to
a ,le in the /tm* directory) use a command li$e this'
R mys+ldum* (u root (* ((no(create(in%o ?
((ta&Q/tm* TUTARI"LS tutorialsNt&l
*assword OOOOOO
-x*orting Ta&le >ontents or <e,nitions in SQL Pormat'
To ex*ort a ta&le in SQL %ormat to a ,le) use a command li$e this'
R mys+ldum* (u root (* TUTARI"LS tutorialsNt&l G dum*!txt
*assword OOOOOO
This will a create ,le having content as %ollows'
(( MySQL dum* 8!E7
((
(( Host' localhost <ata&ase' TUTARI"LS
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(( Server version 7!E7!48
((
(( Ta&le structure %or ta&le btutorialsNt&lb
((
>R-"T- T"#L- tutorialsNt&l B
tutorialNid intBLLC NAT NULL autoNincrement)
tutorialNtitle varcharBL55C NAT NULL de%ault ..)
tutorialNauthor varcharBV5C NAT NULL de%ault ..)
su&missionNdate date de%ault NULL)
RIM"R: T-: BtutorialNidC)
UNIQU- T-: "UTHARNIN<-X BtutorialNauthorC
C T:-QMyIS"MI
((
(( <um*ing data %or ta&le btutorialsNt&lb
((
INS-RT INTA tutorialsNt&l
D"LU-S BL).Learn H.).Wohn oul.).E55](54(EV.CI
INS-RT INTA tutorialsNt&l
D"LU-S BE).Learn MySQL.)."&dul S.).E55](54(EV.CI
INS-RT INTA tutorialsNt&l
D"LU-S B7).W"D" Tutorial.).SanFay.).E55](54(59.CI
To dum* multi*le ta&les) name them all %ollowing the data&ase name
argument! To dum* an entire data&ase) don.t name any ta&les a%ter the
data&ase as %ollows'
R mys+ldum* (u root (* TUTARI"LS G data&aseNdum*!txt
*assword OOOOOO
To &ac$ u* all the data&ases availa&le on your host) use the %ollowing'
R mys+ldum* (u root (* ((all(data&ases G data&aseNdum*!txt
*assword OOOOOO
The ((all(data&ases o*tion is availa&le as o% MySQL 7!E7!LE!
This method can &e used to im*lement a data&ase &ac$u* strategy!
>o*ying Ta&les or <ata&ases to "nother Host'
I% you want to co*y ta&les or data&ases %rom one MySQL server to another)
then use mys+ldum* with data&ase name and ta&le name!
Run the %ollowing command at source host! This will dum* com*lete data&ase
into dum*!txt ,le'
R mys+ldum* (u root (* data&aseNname ta&leNname G dum*!txt
*assword OOOOO
:ou can co*y com*lete data&ase without using a *articular ta&le name as
ex*lained a&ove!
Now) %t* dum*!txt ,le on another host and use the %ollowing command!
#e%ore running this command) ma$e sure you have created data&aseNname
on destination server!
R mys+l (u root (* data&aseNname X dum*!txt
*assword OOOOO
"nother way to accom*lish this without using an intermediary ,le is to send
the out*ut o% mys+ldum* directly over the networ$ to the remote MySQL
server! I% you can connect to &oth servers %rom the host where the coo$&oo$
data&ase resides) use this command'
R mys+ldum* (u root (* data&aseNname ?
states K mys+l (h other(host!com data&aseNname
The mys+ldum* hal% o% the command connects to the local server and writes
the dum* out*ut to the *i*e! The mys+l hal% o% the command connects to the
remote MySQL server on otherhost!com! It reads the *i*e %or in*ut and sends
each statement to the other(host!com server!
There are two sim*le ways in MySQL to load data into MySQL data&ase %rom
a *reviously &ac$ed u* ,le!
Im*orting <ata with LA"< <"T"'
MySQL *rovides a LA"< <"T" statement that acts as a &ul$ data loader!
Here.s an exam*le statement that reads a ,le dum*!txt %rom your current
directory and loads it into the ta&le myt&l in the current data&ase'
mys+lG LA"< <"T" LA>"L INPIL- .dum*!txt. INTA T"#L- myt&lI
I% the LA>"L $eyword is not *resent) MySQL loo$s %or the data,le on the
server host using loo$ing into a&solute *athname %ully s*eci,es the location
o% the ,le) &eginning %rom the root o% the ,lesystem! MySQL reads the ,le
%rom the given location!
#y de%ault) LA"< <"T" assumes that data,les contain lines that are
terminated &y line%eeds BnewlinesC and that data values within a line are
se*arated &y ta&s!
To s*eci%y a ,le %ormat ex*licitly) use a PI-L<S clause to descri&e the
characteristics o% ,elds within a line) and a LIN-S clause to s*eci%y the line(
ending se+uence! The %ollowing LA"< <"T" statement s*eci,es that the
data,le contains values se*arated &y colons and lines terminated &y carriage
returns and new line character'
mys+lG LA"< <"T" LA>"L INPIL- .dum*!txt. INTA T"#L- myt&l
(G PI-L<S T-RMIN"T-< #: .'.
(G LIN-S T-RMIN"T-< #: .?r?n.I
LA"< <"T" assumes the columns in the data,le have the same order as
the columns in the ta&le! I% that.s not true) you can s*eci%y a list to indicate
which ta&le columns the data,le columns should &e loaded into! Su**ose
your ta&le has columns a) &) and c) &ut successive columns in the data,le
corres*ond to columns &) c) and a! :ou can load the ,le li$e this'
mys+lG LA"< <"T" LA>"L INPIL- .dum*!txt.
(G INTA T"#L- myt&l B&) c) aCI
Im*orting <ata with mys+lim*ort
MySQL also includes a utility *rogram named mys+lim*ort that acts as a
wra**er around LA"< <"T" so that you can load in*ut ,les directly %rom the
command line!
To load a data %rom dum*!txt into myt&l) use %ollowing command at UNIX
*rom*t!
R mys+lim*ort (u root (* ((local data&aseNname dum*!txt
*assword OOOOO
I% you use mys+lim*ort) command(line o*tions *rovide the %ormat s*eci,ers!
mys+lim*ort commands that corres*ond to the *receding two LA"< <"T"
statements loo$ li$e this'
R mys+lim*ort (u root (* ((local ((,elds(terminated(&yQM'M ?
((lines(terminated(&yQM?r?nM data&aseNname dum*!txt
*assword OOOOO
The order in which you s*eci%y the o*tions doesn.t matter %or mys+lim*ort)
exce*t that they should all *recede the data&ase name!
The mys+lim*ort statement uses the ((columns o*tion to s*eci%y the column
order'
R mys+lim*ort (u root (* ((local ((columnsQ&)c)a ?
data&aseNname dum*!txt
*assword OOOOO
Handling Quotes and S*ecial >haracters'
The PI-L<S clause can s*eci%y other %ormat o*tions &esides T-RMIN"T-< #:!
#y de%ault) LA"< <"T" assumes that values are un+uoted and inter*rets the
&ac$slash B?C as an esca*e character %or s*ecial characters! To indicate the
value +uoting character ex*licitly) use -N>LAS-< #:I MySQL will stri* that
character %rom the ends o% data values during in*ut *rocessing! To change
the de%ault esca*e character) use -S>"-< #:!
;hen you s*eci%y -N>LAS-< #: to indicate that +uote characters should &e
stri**ed %rom data values) it.s *ossi&le to include the +uote character literally
within data values &y dou&ling it or &y *receding it with the esca*e character!
Por exam*le) i% the +uote and esca*e characters are M and ?) the in*ut value
MaMM&?McM will &e inter*reted as aM&Mc!
Por mys+lim*ort) the corres*onding command(line o*tions %or s*eci%ying
+uote and esca*e values are ((,elds(enclosed(&y and ((,elds(esca*ed(&y

Вам также может понравиться