TweetFollow Us on Twitter

MySQL, Part Deux

Volume Number: 21 (2005)
Issue Number: 4
Column Tag: Programming

Getting Started

by Dave Mark

MySQL, Part Deux

In last month's column, I walked you through the process of installing and securing MySQL on your own Mac. Having PHP and MySQL installed on your local machine is a great way to learn about these two important technologies. You can build databases and script them via PHP without a net connection, and without having to wait for files to FTP each time you make a change. If you haven't already done so, go back and review the PHP and MySQL installation columns and make sure they are both up and running.

    If you are new to this column (I know we've had a bunch of new subscribers lately), go to http://www.php.com and http://www.mysql.com and go through the installation process. First install PHP, then install MySQL. If you find the instructions on those sites a bit daunting, there are a number of tutorials for each. Use google. They're pretty easy to find.

Set Up a MySQL Alias

Before we start playing with MySQL, you'll want to set up an alias, so your Unix shell knows how to find the installed mysql executable. For those of you relatively new to Unix, an alias is a shorthand way of referring to a longer command. Here's an example that I find useful. I frequently use the Unix "find" command to locate files on my hard drive. Here's a typical find command:

find . -name "*.mp3"

This command searches the current directory (".") for any files having a name that ends with ".mp3". Try this command yourself. Launch the Terminal application (you'll find it in the Utilities subfolder). When your Terminal window appears, type the command above. Obviously, your results will depend on how many mp3 files you have in the current directory.

Now type this command:

echo $SHELL

This command tells you what shell you are running. Chances are very good that you are running the bash shell (Bourne Again SHell), and the command will return this result:

/bin/bash

If you are using a different shell, try following along anyway. Worst case, you'll just have to use the long form to launch mysql. I'll show you how to do that in a bit.

Assuming you do have a compatible shell, try typing this command:

alias

This command lists your current aliases. If you've never set up any aliases, when you hit return, you'll just get your prompt back.

Now let's set up an alias for the find command. Type this command:

alias fnd='find . -name'

You've just created an alias. Every time you type fnd, the shell will substitute the string "find . -name". To check this, type the command:

alias

The shell should list your new alias:

alias fnd='find . -name'

To test your new alias, type this command:

fnd "*.mp3"

This command should behave exactly the same as your original find command. Cool, you've just created your first alias!

The alias we just created is temporary and will disappear as soon as we logout by closing the window or quitting Terminal. Rather than having to redo all your aliases each time you login or start a new Terminal session, there is a more permanent solution. Each time you login, the bash shell looks for a file in your home directory named .profile and executes, as shell commands, each line in the file.

Take some time to learn either vi or emacs, the two better-known Unix text editors, then edit your .profile and append any alias commands you'd like to have. At the very least, add this alias to your profile:

alias mysql='/usr/local/mysql/bin/mysql'

Note that when you add an alias to your .profile, the alias command won't be executed until you log out and log back in again or close your Terminal window and open a new one. One nice way to re-run your .profile is to use this command:

source .profile

Here's what happened when I ran this command, then ran the alias command to check my current list of aliases:

Dave-Marks-Computer:~ davemark$ alias
alias fnd='find / -name'
Dave-Marks-Computer:~ davemark$ source .profile
Dave-Marks-Computer:~ davemark$ alias
alias fnd='find / -name'
alias mysql='/usr/local/mysql/bin/mysql'

The first alias command only found my fnd alias. I then ran .profile and checked my aliases again and, lo and behold, my new mysql alias was added to the list. Cool!

Another command worth noting is the unalias command. For example:

Dave-Marks-Computer:~ davemark$ unalias fnd
Dave-Marks-Computer:~ davemark$ alias
alias mysql='/usr/local/mysql/bin/mysql'

I used unalias to remove the fnd alias from the list. Of course, since I added that alias to my .profile, as soon as I log back in, the alias will be back.

    Want to learn more about the bash shell? Check out Learning the bash Shell by Cameron Newham & Bill Rosenblatt from our friends at O'Reilly. They just released a 3rd Edition of the book and it looks great. It'll walk you through things like command history, command-line editing, command completion, shell programming, flow control, signal handling, etc. Lots of great stuff, very accessible.

Getting Started with MySQL

With your new, mysql, alias in place, we're ready to launch the MySQL monitor and play a bit. Start by launching mysql:

mysql -u root -p

This command executes the mysql program located in /usr/local/mysql/bin/ (take another look at the alias to see where this path came from). It starts mysql logging in as the user root and tells mysql to prompt you for a password. As a reminder, in last month's column, we added a password to the root account for obvious security reasons. Remember, MySQL maintains its own list of users. The MySQL root is not the same as your computer's root account. They just share the same name.

Here's what I saw when I started mysql:

Dave-Marks-Computer:~ davemark$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3 to server version: 4.1.8-standard

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Building a Database and Table

Our first step is to create a database. We'll then populate the database with tables. Each table will have rows and columns and is where the actual data resides.

Our database will be called pets. Within pets, we'll create a table called dogs. As you might imagine, we could also create a table called cats and another table called fish.

Let's start by asking mysql to tell us what databases already exist:

mysql> show databases;
+----------+
| Database |
+----------+
| mysql    |
| test     |
+----------+
2 rows in set (0.07 sec)

mysql>

MySQL ships with two databases. The mysql database contains all the user access privileges. You won't add to that database. The test database is for you to play with. After you finish with this column, go ahead and add your own tables to it. For now, we're going to create a new database called pets. Start by typing this command:

mysql> create database pets
    ->

Hmmm...Notice that mysql did not process your command. Instead, it prompted you with a -> prompt. That's because mysql expects you to end each command with a semicolon (;). One of the nice things about this approach is that you can break complex commands across multiple lines. When you are ready to terminate the command, end the line with a semi.

To finish the previous command, just type a semicolon and mysql will create your pets database:

mysql> create database pets
    -> ;
Query OK, 1 row affected (0.39 sec)

mysql>

Now let's check to see if the database was actually created:

mysql> show databases;
+----------+
| Database |
+----------+
| mysql    |
| pets     |
| test     |
+----------+
3 rows in set (0.63 sec)

mysql>

Note that splitting the command over three lines would work equally well:

mysql> show
    -> databases
    -> ;
+----------+
| Database |
+----------+
| mysql    |
| pets     |
| test     |
+----------+
3 rows in set (0.00 sec)

mysql>

Cool! So now we have a pets database. Before we add a table to the database, let's see what tables already exist:

mysql> show tables;
ERROR 1046 (3D000): No database selected
mysql>

The problem here is that we haven't told mysql which database to look in. Try this command:

mysql> show tables from pets;
Empty set (0.00 sec)

mysql>

That's better. As you can see, the pets database does not yet contain any tables. Rather than have to specify a database with every command that refers to a table, we can issue this command:

mysql> use pets;

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

Database changed
mysql>

From now on, when we refer to a table name or issue a table command, mysql will assume we are using the pets database.

Let's create a dogs table:

mysql> create table dogs( 
    -> breed varchar(60),
    -> age int(2),  
    -> dogID int(10) auto_increment primary key );
Query OK, 0 rows affected (0.39 sec)

mysql>

Tables have columns and rows. Each column represents a specific type of data you want stored in your table. You can think of the table definition as a sort of struct definition, with each field as a column header and each row as a specific instance of a struct with all the fields filled in. Our create table command defined the table as having 3 columns. The first column contains a 60 character string. The second character contains a 2-byte integer.

The third column contains a 10-byte integer that will act as the primary key to our database. You'll use this key to do lookups. We'll do that a bit later on in the column. The auto_increment tag tells mysql to assign the next higher number each time a new row is created in the table. This technique works as long as the row is added with this field set to 0. So the first dog added to the table will automatically get a dogID of 1. The next one will get a dogID of 2. And so on. As long as the row is created with a dogID of 0, the dogID field will be filled with the next available dogID.

Let's create a dog:

mysql> insert into dogs values ('poodle', 8, 0 );
Query OK, 1 row affected (0.37 sec)

mysql>

This dog will have a breed of 'poodle', an age of 8, and will get assigned a dogID of 1. Let's verify that:

mysql> select * from dogs;
+-------- +------ +------ +
| breed   | age   | dogID |
+-------- +------ +------ +
| poodle  |   8   |   1   |
+-------- +------ +------ +
1 row in set (0.33 sec)

mysql>

The select command let's you retrieve data from the table. The * is a wildcard, allowing us to retrieve all the rows in the table. Since we've only created a single row, we only get back a single row. Makes sense.

Let's add a second row to the table:

mysql> insert into dogs values ('spaniel',7,0);
Query OK, 1 row affected (0.33 sec)

mysql>

Again, we used 0 as the third argument so we benefit from the auto_increment. Let's take a look at all the rows in our table now that we've added a second row:

mysql> select * from dogs;
+-------- +------ +------ +
| breed   | age   | dogID |
+-------- +------ +------ +
| poodle  |   8   |   1   |
| spaniel |   7   |   2   |
+-------- +------ +------ +
2 rows in set (0.36 sec)

mysql>

Makes sense, right? This variation of select retrieves the data, but orders it by age:

mysql> select * from dogs order by age asc;     
+-------- +------ +------ +
| breed   |  age  | dogID |
+-------- +------ +------ +
| spaniel |   7   |   2   |
| poodle  |   8   |   1   |
+-------- +------ +------ +
2 rows in set (0.00 sec)

mysql>

The asc in the command above stands for ascending. We could have used desc if we wanted the data in descending order.

Now let's change our table data by using the update command. Before you read on, take a look at this command and see if you can figure out what it will do:

mysql> update dogs set breed='mutt' where dogID=1;
Query OK, 1 row affected (0.39 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql>

Got it? Take a look:

mysql> select * from dogs;
+-------- +------ +------ +
| breed   |  age  | dogID |
+-------- +------ +------ +
| mutt    |   8   |   1   |
| spaniel |   7   |   2   |
+-------- +------ +------ +
2 rows in set (0.01 sec)

mysql>

The update command set the breed field to the value of 'mutt' in the row with a dogID of 1. So we changed our poodle into a mutt. Cool!

Now, let's delete the spaniel:

mysql> delete from dogs where dogID=2;
Query OK, 1 row affected (0.33 sec)

mysql>

This delete command will delete all rows from the dogs table with a dogID of 2. Of course, there's only one row that fits that description. Here's the results:

mysql> select * from dogs;
+------ +------ +------ +
| breed |  age  | dogID |
+------ +------ +------ +
| mutt  |   8   |   1   |
+------ +------ +------ +
1 row in set (0.00 sec)

mysql>

As you can see, we're down to just the one row.

Here's a slightly more complex select command:

mysql> select * from dogs where age>4 AND dogID <20;
+------ +------ +------ +
| breed |  age  | dogID |
+------ +------ +------ +
| mutt  |   8   |   1   |
+------ +------ +------ +
1 row in set (0.34 sec)

mysql>

Reading the Documentation

Before we close, here are a few links to help you find your way through the official MySQL web site and documentation. For starters, you'll want to explore the top level at:

http://www.mysql.com

Now, click on the Developer Zone tab and spend a bit of time on this page. Once you have your sea legs, click on the Documentation sub-tab on the Developer Zone page. Here's the direct link:

http://dev.mysql.com/doc/

There are a number of important links on this page (See Figure 1). The second link is a link to a hyperlinked, online version of the MySQL documentation. This link is followed by various links that allow you to download the entire set of documentation to your hard drive. Start by exploring the second link, see if this form of documentation works for you. If not, download the form that works best for you.


Figure 1. The MySQL Reference Manual links

Assuming you've already installed MySQL and followed along with this column, a great place to start reading is this page:

http://dev.mysql.com/doc/mysql/en/tutorial.html

You should recognize a lot of the commands at this point and, hopefully, this column will have filled in enough of the picture so the stuff you haven't yet seen will make sense.

Until Next Month...

Try playing around with the dog table yourself. Add a bunch of rows, make the table more complex. In next month's column, we're going to use PHP to access a MySQL database and table from a web page. Using the mysql monitor is an excellent way to create your tables in the first place, and an excellent tool to check on and repair any data that gets a little futzy. But the real cool stuff happens when you mix MySQL and PHP. Fun, fun, fun!

Oh, and be sure to take a look at Ben Waldie's new Automator book on http://spiderworks.com. It totally rocks. Go, Ben!


Dave Mark is a long-time Mac developer and author and has written a number of books on Macintosh development. Dave has been writing for MacTech since its birth! Be sure to check out the new Learn C on the Macintosh, Mac OS X Edition at http://www.spiderworks.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.