Perl Connecting to the MySQL Server, Selecting a Database, and Disconnecting

addit ional com put at ions aft er accessing t he server, t he connect ion will be held open longer t han necessary. I t s also preferable t o close t he connect ion explicit ly. I f a program sim ply t erm inat es wit hout closing t he connect ion, t he MySQL server event ually not ices, but shut t ing down t he connect ion explicit ly allows t he server t o perform an orderly close on it s end im m ediat ely. Our exam ple program s for each API in t his sect ion show how t o connect t o t he server, select t he cookbook dat abase, and disconnect . However, on occasion you m ight want t o writ e a MySQL program t hat doesnt select a dat abase. This would be t he case if you plan t o issue a query t hat doesnt require a default dat abase, such as SHOW VARIABLES or SHOW DATABASES . Or perhaps youre writ ing an int eract ive program t hat connect s t o t he server and allows t he user t o specify t he dat abase aft er t he connect ion has been m ade. To cover such sit uat ions, t he discussion for each API also indicat es how t o connect wit hout select ing any dat abase. The Meaning of localhost in MySQL One of t he param et ers you specify when connect ing t o a MySQL server is t he host w here t he server is running. Most program s t reat t he host nam e localhost and t he I P address 127.0.0.1 as synonym ous. Under Unix, MySQL program s behave different ly; by convent ion, t hey t reat t he host nam e localhost specially and at t em pt t o connect t o t he server using a Unix dom ain socket file. To force a TCP I P connect ion t o t he local host , use t he I P address 127.0.0.1 rat her t han t he host nam e localhost . Under Windows, localhost and 127.0.0.1 are t reat ed t he sam e, because Windows doesnt have Unix dom ain socket s. The default port is 3306 for TCP I P connect ions. The pat hnam e for t he Unix dom ain socket varies, alt hough it s oft en t m p m ysql.sock. The recipes indicat e how t o specify t he socket file pat hnam e or TCP I P port num ber explicit ly if you dont want t o use t he default .

2.2.4 Perl

To writ e MySQL script s in Perl, you should have t he DBI m odule inst alled, as well as t he MySQL-specific DBI driver m odule, DBD: : m ysql. Appendix A cont ains inform at ion on get t ing t hese if t heyre not already inst alled. There is an older int erface for Perl nam ed MysqlPerl, but it s obsolet e and is not covered here. Here is a sim ple Perl script t hat connect s t o t he cookbook dat abase, t hen disconnect s: usrbinperl -w connect.pl - connect to the MySQL server use strict; use DBI; my dsn = DBI:mysql:host=localhost;database=cookbook; my dbh = DBI-connect dsn, cbuser, cbpass or die Cannot connect to server\n; print Connected\n; dbh-disconnect ; print Disconnected\n; exit 0; To t ry t he script , creat e a file nam ed connect .pl t hat cont ains t he preceding code. To run connect .pl under Unix, you m ay need t o change t he pat hnam e on t he first line if your Perl program is locat ed som ewhere ot her t han usr bin perl. Then m ake t he script execut able wit h chm od + x, and invoke it as follows: chmod +x connect.pl .connect.pl Connected Disconnected Under Windows, chm od will not be necessary; you run connect .pl like t his: C:\ perl connect.pl Connected Disconnected I f you have a filenam e associat ion set up t hat allows .pl files t o be execut ed direct ly from t he com m and line, you need not invoke Perl explicit ly: C:\ connect.pl Connected Disconnected For m ore inform at ion on running program s t hat youve writ t en yourself, see t he sidebar Using Execut able Program s in Recipe 1.33 . The - w opt ion t urns on warning m ode so t hat Perl produces warnings for any quest ionable const ruct s. Our exam ple script has no such const ruct s, but it s a good idea t o get in t he habit of using - w ; as you m odify your script s during t he developm ent process, youll oft en find t hat Perl has useful com m ent s t o m ake about t hem . The use strict line t urns on st rict variable checking and causes Perl t o com plain about any variables t hat are used wit hout having been declared first . This is a sensible precaut ion because it helps find errors t hat m ight ot herwise go undet ect ed. The use DBI st at em ent t ells Perl t hat t he program needs t o use t he DBI m odule. I t s unnecessary t o load t he MySQL driver m odule DBD: : m ysql explicit ly, because DBI will do t hat it self when t he script connect s t o t he dat abase server. The next t wo lines est ablish t he connect ion t o MySQL by set t ing up a dat a source nam e DSN and calling t he DBI connect m et hod. The argum ent s t o connect are t he DSN, t he MySQL usernam e, t he password, and any connect ion at t ribut es you want t o specify. The DSN is required. The ot her argum ent s are opt ional, alt hough usually it s necessary t o supply a nam e and password t o get very far. The DSN specifies which dat abase driver t o use and ot her opt ions indicat ing where t o connect . For MySQL program s, t he DSN has t he form at DBI:mysql: options . The t hree com ponent s of which have t he following m eanings: • The first com ponent is always DBI . I t s not case sensit ive; dbi or Dbi w ould do j ust as well. • The second com ponent t ells DBI which dat abase driver t o use. For MySQL, t he nam e m ust be mysql and it is case sensit ive. You cant use MySQL , MYSQL , or any ot her variat ion. • The t hird com ponent , if present , is a sem icolon-separat ed list of name = value pairs specifying addit ional connect ion opt ions. The order of any opt ions you provide doesnt m at t er. For our purposes here, t he t wo m ost relevant opt ions are host and database . They specify t he host nam e where t he MySQL server is running and t he dat abase you want t o use. Not e t hat t he second colon in t he DSN is not opt ional, even if you dont specify any opt ions. Given t his inform at ion, t he DSN for connect ing t o t he cookbook dat abase on t he local host localhost looks like t his: DBI:mysql:host=localhost;database=cookbook I f you leave out t he host opt ion, it s default value is localhost . Thus, t hese t wo DSNs are equivalent : DBI:mysql:host=localhost;database=cookbook DBI:mysql:database=cookbook I f you om it t he database opt ion, no dat abase is select ed when you connect . The second and t hird argum ent s of t he connect call are your MySQL usernam e and password. You can also provide a fourt h argum ent following t he password t o specify at t ribut es t hat cont rol DBI s behavior when errors occur. By default , DBI print s error m essages when errors occur but does not t erm inat e your script . That s why connect .pl checks whet her connect ret urns undef t o indicat e failure: my dbh = DBI-connect dsn, cbuser, cbpass or die Cannot connect to server\n; Ot her error-handling st rat egies are possible. For exam ple, you can t ell DBI t o t erm inat e t he script aut om at ically when an error occurs in a DBI call by disabling t he PrintError at t ribut e and enabling RaiseError inst ead. Then you dont have t o check for errors yourself: my dbh = DBI-connect dsn, user_name, password, {PrintError = 0, RaiseError = 1}; Error handling is discussed furt her in Recipe 2.3 . Assum ing t hat connect succeeds, it ret urns a dat abase handle t hat cont ains inform at ion about t he st at e of t he connect ion. I n DBI parlance, references t o obj ect s are called handles. Lat er well see ot her handles, such as st at em ent handles t hat are associat ed wit h part icular queries. DBI script s in t his book convent ionally use dbh and sth t o signify dat abase and st at em ent handles. 2 .2 .4 .1 Addit ion a l con n e ct ion pa r a m e t e r s For connect ions t o localhost , you can provide a mysql_socket opt ion in t he DSN t o specify t he pat h t o t he Unix dom ain socket : my dsn = DBI:mysql:host=localhost;mysql_socket=vartmpmysql.sock . ;database=cookbook; The mysql_socket opt ion is available as of MySQL 3.21.15. For non- localhost connect ions, you can provide a port opt ion t o specify t he port num ber: my dsn = DBI:mysql:host=mysql.snake.net;port=3307;database=cookbook;

2.2.5 PHP