TweetFollow Us on Twitter

Your First MySQL Database

Volume Number: 20 (2004)
Issue Number: 1
Column Tag: Programming

Untangling the Web

by Kevin Hemenway

Your First MySQL Database

Creating, administering, and maintaining are pretty easy.

Last month, besides exploring what was different between the Jaguar and Panther web serving configurations, we installed the MySQL database program (specifically, the "value-added" installer from third-party Server Logistics), used the provided System Preference to initialize the database and set the MySQL root password, then confirmed it was running through one of three avenues (log files, the Terminal, or the Activity Monitor).

We've yet to create a MySQL database or insert any data. We betta' rECtififffYYyy!

Exploring The MySQL Helper Programs

Along with the MySQL daemon (where "daemon" is an application that runs all the time, resolutely waiting for something to do), a bunch of other useful helper programs were installed alongside your new database server. Take a look in your /Library/MySQL/bin directory (Figure 1) for the complete list. Some of these programs (like msql2_mysql, make_win_src_distribution, mysql_install, and mysql_install_db) will never be used in normal (or even abnormal) operation. Others (like mysqladmin, mysql_setpermission, mysqlshow and mysqldump) will become regular additions to your MySQL administrating repertoire.

The most negative aspect of these helper utilities is that there's no central place to find information on what they all do. Some, like mysql_config, have no explanations for their purpose (commonly accessible by passing -?, -h, or --help as command line flags), but their source code can be viewed with vi, less, or BBEdit to divine their intent. Others, like mysqlshow, have manual pages that can be accessed with a command like man -M /Library/MySQL/man/ mysqlshow (see "Homework Malignments" for a shortcut), and still others, like mysql_setpermission, are Perl scripts that need an additional module (DBI) not installed by default.


Figure 1: A number of additional MySQL utilities were installed.

Since the DBI Perl module plays an important part (both in the mysql_setpermission script and any future database interaction in Perl), we'll install that onto our machines before we go much further. Prior to starting, however, we'll need to fix a bug that wasn't corrected in time for Panther's public release. Open /System/Library/Perl/5.8.1/darwin-thread-multi-2level/Config.pm in an authenticating text editor (I prefer BBEdit, but you can use something like sudo vi $filename), and look for the following line:

ld='MACOSX_DEPLOYMENT_TARGET=10.3 cc'

Add the word env, creating the following correction:

ld='env MACOSX_DEPLOYMENT_TARGET=10.3 cc'

After saving the file, we've got one more annoyance to take care of. Remember how we set the MySQL root password so that our database would be reasonably secure? Welp, the Perl module we're about to install requires access to MySQL to run some tests, and there's no simple way to give it what it needs without temporarily blanking out that root password. Using the installed MySQL System Preference doesn't allow us to set a null value, so we'll need to run the following in the shell: /Library/MySQL/bin/mysqladmin -u root -p password "" (no spaces between those quotes). You'll be prompted for your current password... once entered, the root password will be set to nothing.

We're now ready to start the DBI installation process. To do so, we're going to use Perl's CPAN (the "Comprehensive Perl Archive Network") to automatically download the module, check and enable any prerequisites, ensure everything is working properly with a bevy of tests, and finally, install the modules for regular use.

Normally, to start CPAN, we'd simply enter sudo perl -MCPAN -eshell at the command line. However, the module we'll be installing needs to know a bit about our MySQL installation so, just this once, we're going to use the following commands instead. These will, for the duration of our current shell, add the MySQL bin directory to the lookup path (instructions on how to set these permanently are available in "Homework Malignments"):

# if you're using the tcsh shell:
setenv PATH ${PATH}:/Library/MySQL/bin
sudo perl -MCPAN -eshell

# if you're using the bash shell, use the following:
PATH=$PATH:/Library/MySQL/bin sudo perl -MCPAN -eshell

If this is your first time using CPAN, you may be asked oodles and oodles of configuration questions, including whether you're using proxies, what CPAN sites you want to download from, and so on. In most cases, you can just accept the defaults. Eventually, you'll end up at a command prompt that looks something like this:

shell -- CPAN exploration and modules installation (v1.76)
ReadLine support enabled

cpan>

Now, type install Bundle::DBD::mysql. This will install a bunch of modules related to the MySQL DBD ("database definition") of Perl's DBI ("database interface")--you'll see a dozen screens of information fly by before the process is finished. Depending on your CPAN configuration, you may be asked to follow some missing module prerequisite, which you should generally always agree to.

If the CPAN process complains about its inability to download modules from any of the mirror sites you chose during configuration, you probably have Panther's internal firewall enabled. Cancel the CPAN process, execute export FTP_PASSIVE=1 in the shell, and then start the CPAN process again. More information is available in "Homework Malignments".

If any critical errors occur, the install process will stop... in our case, we should have received a few during the testing phase of DBD::mysql (Figure 2). We could go nuts about actually hunting down and fixing these errors that caused the integrity checks to fail (thus canceling the installation), but honestly, you can "cheat" and force things forward anyways. Some will cluck at me for saying so, but run the following CPAN command to force the installation: force install Bundle::DBD::mysql. For more information about the failing tests, reference http://www.mail-archive.com/macosx@perl.org/msg05834.html.


Figure 2: Failures in the DBD::mysql module can be ignored.

Once the forced installation has finished, you'll be returned to the standard cpan> prompt. Type exit to finish the process, and then be sure to reset the MySQL root password back to what it was before. You can do this either from the command line (using /Library/MySQL/bin/mysqladmin -u root password "password") or by using the MySQL System Preference (Figure 3).


Figure 3: Using the System Preference to set the MySQL root password.

Creating Our First Database

The larger purpose of getting the Perl DBI and DBD modules installed was to use one of the MySQL helper utilities to create a new database, a new MySQL user, and set the proper permissions for access thereafter. There are many different ways and avenues this can be done; I happen to think that mysql_setpermission, a utility that requires DBI, is one of the easiest and friendlier paths to speed down.

We can start the mysql_setpermission script one of two different ways. Without any additional command line flags, it will attempt to connect to the MySQL database as the current user: morbus, in my case. Since that user has yet to be created within MySQL (remember, MySQL users and permissions have nothing to do with Linux users and permissions), I'll receive a disheartening error about lack of access:

~ > /Library/MySQL/bin/mysql_setpermission
Password for user to connect to MySQL: 
Can't make a connection to the mysql server.
 The error: Access denied for user: 'morbus@localhost'  
 (Using password: YES) at /Library/MySQL/bin/mysql_
 setpermission line 70, <STDIN> line 1.

We can solve this one of two ways: temporarily becoming the root user with sudo /Library/MySQL/bin/mysql_setpermission, or by passing the MySQL username as a command line flag with /Library/MySQL/bin/mysql_setpermission --user root. Regardless of the method, we'll reach a menu with numerous possibilities (Figure 4).


Figure 4: The starting menu of mysql_setpermission.

Since we've yet to create a database or MySQL user, we'll want to choose the second option, which allows us to do both. You'll be asked the name of the database to create, the username and password for the new MySQL user (passwords are heartily recommended if you plan on allowing the new user to modify data), and the hosts this user can access the database from. In our example (Figure 5), the new mactech database can be accessed by davemarksman from any host (represented by the % character). The host restriction determines whether other programs on other servers can connect to the mactech database. When a normal web visitor accesses any of our connecting code, it's considered localhost access (the visitor uses our Apache web server, which runs our PHP code, which connects to our MySQL installation.)


Figure 5: Adding a new MySQL database and user.

By default, the user that is created will have very slim access to the specified database (they'll only be able to read data with SELECT, not modify or delete). Since our next article will talk about inserting, modifying, and deleting, we'll want to next choose option 5, which allows us to give davemarksman heightened privileges (Figure 6).


Figure 6: Choosing the database to give heightened user privileges to.

Once you've created your database and configured your user permissions, you can exit the program by choosing option 0, which will send you back to the shell prompt. You can confirm your database has been created by running /Library/MySQL/bin/mysqlshow -u root -p, which gives output something like:

~ > /Library/MySQL/bin/mysqlshow --user root -p
Enter password: 
+-----------+
| Databases |
+-----------+
| mactech   |
| mysql     |
| test      |
+-----------+

Homework Malignments

I shall no longer prophesize about what will be in the next article, as I seemingly always overshoot my estimates. Instead, students may contact the teacher at morbus@disobey.com.

When you're in the Terminal, there are two environment variables that help control how much typing you have to do: PATH and MANPATH. The first controls what directories will be looked into when you attempt to run a binary program without a full path (like vi compared to /usr/bin/vi), and the second determines what directories are looked into for manual pages. You can see their current configuration by typing printenv in your Terminal. To make working with the MySQL shell programs easier, you'll want to add /Library/MySQL/bin to your PATH, and /Library/MySQL/man to your MANPATH. In Panther, which uses the bash shell by default, add PATH="$PATH:/Library/MySQL/bin" to your (possibly non-existent) /Users/username/.bash_profile. Then, with an authenticating text editor, add OPTIONAL_MANPATH /Library/MySQL/man and OPTIONAL_MANPATH /man to the /etc/manpath.config file. With that finished, restart your Terminal, and you should be able to type man mysqlshow.

You can also add export FTP_PASSIVE=1 to the .bash_profile (see previous Malignment). This instructs CPAN (specifically, the Net::FTP Perl module) to use passive file transfer mode which, for some, is required when the Panther firewall is enabled. Thanks to the macosx@perl.org mailing list for that tidbit.


Kevin Hemenway, coauthor of Mac OS X Hacks and Spidering Hacks, is better known as Morbus Iff, the creator of disobey.com, which bills itself as "content for the discontented." Publisher and developer of more home cooking than you could ever imagine (like the popular open-sourced aggregator AmphetaDesk, the best-kept gaming secret Gamegrene.com, the ever ignorable Nonsense Network, etc.), he has started to self-teach indexing and cataloging skills for his . .. . . "media collection". Contact him at morbus@disobey.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »

Price Scanner via MacPrices.net

Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.