Home > Articles > Data > MySQL

Why MySQL?

This chapter is from the book

5.2 TUTORIAL

Following the Swiss Army knife theory (20 percent of the functions give you 80 percent of the utility), a few SQL commands go a long way to facilitate learning MySQL/Perl/DBI.

To illustrate these, we create a simple database containing information about some (fictional) people. Eventually, we'll show how to enter this information from a form on the Web (see Chapter 7), but for now we interface with SQL directly.

First, try to make a connection to our MySQL server as the root MySQL user:

$ mysql -u root 

NOTE

The MySQL root user is different from the Linux root user. The MySQL root user is used to administer the MySQL server only.

If you see the following output:

ERROR 2002: Can't connect to local MySQL server through socket 
´/var/lib/mysql/mysql.sock´(2) 

it likely means the MySQL server is not running. If your system is set up securely, it shouldn't be running, because you had no reason, before now, for it to be running. Use chkconfig as root to make sure it starts the next time the machine boots, and then start it by hand as follows:

chkconfig mysqld on
/etc/init.d/mysqld start

Now you should be able to connect (not logged in as the Linux root user):

$ mysql -u root 

If not, see the MySQL log file at /var/log/mysqld.log. If so, you'll see a welcome message and the MySQL prompt:

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3 to server version: 3.23.36

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

mysql>

As suggested, enter help; at the prompt. A list of MySQL commands (not to be confused with SQL commands) will be displayed. These allow you to work with the MySQL server. For grins, enter status; to see the status of the server.

To illustrate these commands, we will create a database called people that contains information about people and their ages.

5.2.1 The SHOW DATABASES and CREATE DATABASE Commands

First, we need to create the new database. Check the current databases to make sure a database of that name doesn't already exist; then create the new one, and verify the existence of the new database:

mysql> SHOW DATABASES;
+----------+
| Database |
+----------+
| mysql    |
| test     |
+----------+
2 rows in set (0.00 sec)

mysql> CREATE DATABASE people;
Query OK, 1 row affected (0.00 sec)

mysql> SHOW DATABASES;
+----------+
| Database |
+----------+
| mysql    |
| people   |
| test     |
+----------+
3 rows in set (0.00 sec)

SQL commands and subcommands (in the previous example, CREATE is a command; DATABASE is its subcommand) are case-insensitive. The name of the database (and table and field) are case sensitive. It's a matter of style whether one uses uppercase or lowercase, but traditionally the SQL commands are distinguished by uppercase.

One way to think of a database is as a container for related tables. A table is a collection of rows, each row holding data for one record, each record containing chunks of information called fields.

5.2.2 The USE Command

Before anything can be done with the newly created database, MySQL has to connect to it. That's done with the USE command:

mysql> USE people; 

5.2.3 The CREATE TABLE and SHOW TABLES Commands

Each table within the database must be defined and created. This is done with the CREATE TABLE command.

Create a table named age information to contain an individual's first name, last name, and age. MySQL needs to know what kind of data can be stored in these fields. In this case, the first name and the last name are character strings of up to 20 characters each, and the age is an integer:

mysql> CREATE TABLE age information (
    -> lastname CHAR(20),
    -> firstname CHAR(20),
    -> age INT
    -> );
Query OK, 0 rows affected (0.00 sec)

It appears that the table was created properly (it says OK after all), but this can be checked by executing the SHOW TABLES command. If an error is made, the table can be removed with DROP TABLE.

When a database in MySQL is created, a directory is created with the same name as the database (people, in this example):

# ls -l /var/lib/mysql
total 3
drwx------ 2 mysql mysql 1024 Dec 12 15:28 mysql
srwxrwxrwx 1 mysql mysql 0 Dec 13 07:19 mysql.sock
drwx------ 2 mysql mysql 1024 Dec 13 07:24 people
drwx------ 2 mysql mysql 1024 Dec 12 15:28 test

Within that directory, each table is implemented with three .les:

# ls -l /var/lib/mysql/people
total 10
-rw-rw---- 1 mysql mysql 8618 Dec 13 07:24 age_information.frm
-rw-rw---- 1 mysql mysql 0 Dec 13 07:24 age_information.MYD
-rw-rw---- 1 mysql mysql 1024 Dec 13 07:24 age_information.MYI

mysql> SHOW TABLES;
+------------------+
| Tables_in_people |
+------------------+
| age_information  |
+------------------+
1 row in set (0.00 sec)

This example shows two MySQL datatypes: character strings and integers. Other MySQL data types include several types of integers (for a complete discussion of MySQL's data types, see www.mysql.com/ documentation/mysql/bychapter/manual Reference.html#Column types):

TINYINT

-128 to 127 (signed)

or 0 to 255 (unsigned)

SMALLINT

-32768 to 32767 (signed)

or 0 to 65535 (unsigned)

MEDIUMINT

-8388608 to 8388607 (signed)

or 0 to 16777215 (unsigned)

INTEGER (same as INT)

-2147483648 to 2147483647 (signed)

or 0 to 4294967295 (unsigned)

BIGINT

-9223372036854775808 to 9223372036854775807 (signed)

or 0 to 18446744073709551615 (unsigned)


and floating points:

FLOAT
DOUBLE
REAL (same as DOUBLE)
DECIMAL
NUMERIC (same as DECIMAL)

There are several data types to represent a date:

DATE

YYYY-MM-DD

DATETIME

YYYY-MM-DD HH:MM:SS

TIMESTAMP

YYYYMMDDHHMMSS

or YYMMDDHHMMSS

or YYYYMMDD or YYMMDD

TIME

HH:MM:SS

YEAR

YYYY or YY


The table age information used the CHAR character data type. The following are the other character data types. Several have BLOB in their name—a BLOB is a Binary Large OBject that can hold a variable amount of data. The types with TEXT in their name are just like their corresponding BLOBs except when matching is involved: The BLOBs are case-sensitive, and the

TEXT

s are case-insensitive.

VARCHAR

variable-length string up to 255 characters

TINYBLOB

maximum length 255 characters

TINYTEXT

 

BLOB

maximum length 65535 characters

TEXT

 

MEDIUMBLOB

maximum length 16777215 characters

MEDIUMTEXT

 

LONGBLOB

maximum length 4294967295 characters

LONGTEXT

 


5.2.4 The DESCRIBE Command

The DESCRIBE command gives information about the fields in a table. The fields created earlier—lastname, firstname, and age—appear to have been created correctly.

mysql> DESCRIBE age information;
+-----------+----------+------+-----+---------+-------+
| Field     | Type     | Null | Key | Default | Extra |
+-----------+----------+------+-----+---------+-------+
| lastname  | char(20) | YES  |     | NULL    |       |
| firstname | char(20) | YES  |     | NULL    |       |
| age       | int(11)  | YES  |     | NULL    |       |
+-----------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

The command SHOW COLUMNS FROM age information; gives the same information as DESCRIBE age information; but DESCRIBE involves less typing. (If you're really trying to save keystrokes, you could abbreviate DESCRIBE as DESC.)

5.2.5 The INSERT Command

For the table to be useful, we need to add information to it. We do so with the INSERT command:

mysql> INSERT INTO age information
    -> (lastname, firstname, age)
    -> VALUES (´Wall´, ´Larry´, 46);
Query OK, 1 row affected (0.00 sec)

The syntax of the command is INSERT INTO, followed by the table in which to insert, a list within parentheses of the fields into which information is to be inserted, and the qualifier VALUES followed by the list of values in parentheses in the same order as the respective fields.1

5.2.6 The SELECT Command

SELECT selects records from the database. When this command is executed from the command line, MySQL prints all the records that match the query. The simplest use of SELECT is shown in this example:

mysql> SELECT * FROM age information;
+----------+-----------+------+
| lastname | firstname | age  |
+----------+-----------+------+
| Wall     | Larry     | 46   |
+----------+-----------+------+
1 row in set (0.00 sec)

The * means "show values for all fields in the table"; FROM specifies the table from which to extract the information.

The previous output shows that the record for Larry Wall was added successfully. To experiment with the SELECT command, we need to add a few more records, just to make things interesting:

mysql> INSERT INTO age information
    -> (lastname, firstname, age)
    -> VALUES (´Torvalds´, ´Linus´, 31);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO age information
    -> (lastname, firstname, age)
    -> VALUES (´Raymond´, ´Eric´, 40);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM age information;
+----------+-----------+------+
| lastname | firstname | age  |
+----------+-----------+------+
| Wall     | Larry     | 46   |
| Torvalds | Linus     | 31   |
| Raymond  | Eric      | 40   |
+----------+-----------+------+
3 rows in set (0.00 sec)

There are many ways to use the SELECT command—it's very flexible. First, sort the table based on lastname:

mysql> SELECT * FROM age information
    -> ORDER BY lastname;
+----------+-----------+------+
| lastname | firstname | age  |
+----------+-----------+------+
| Raymond  | Eric      | 40   |
| Torvalds | Linus     | 31   |
| Wall     | Larry     | 46   |
+----------+-----------+------+
3 rows in set (0.00 sec)

Now show only the lastname field, sorted by lastname:

mysql> SELECT lastname FROM age information
    -> ORDER BY lastname;
+----------+
| lastname |
+----------+
| Raymond  |
| Torvalds |
| Wall     |
+----------+
3 rows in set (0.00 sec)

Show the ages in descending order:

mysql> SELECT age FROM age information ORDER BY age DESC;
+------+
| age  |
+------+
| 46   |
| 40   |
| 31   |
+------+
3 rows in set (0.00 sec)

Show all the last names for those who are older than 35:

mysql> SELECT lastname FROM age information WHERE age > 35;
+----------+
| lastname |
+----------+
| Wall     |
| Raymond  |
+----------+
2 rows in set (0.00 sec)

Do the same, but sort by lastname:

mysql> SELECT lastname FROM age information
    -> WHERE age > 35 ORDER BY lastname;
+----------+
| lastname |
+----------+
| Raymond  |
| Wall     |
+----------+
2 rows in set (0.00 sec)

5.2.7 The UPDATE Command

Since the database is about people, information in it can change (people are unpredictable like that). For instance, although a person's birthday is static, their age changes. To change the value in an existing record, we can UPDATE the table. Let's say the fictional Larry Wall has turned 47:

mysql> SELECT * FROM age information;
+----------+-----------+------+
| lastname | firstname | age  |
+----------+-----------+------+
| Wall     | Larry     | 46   |
| Torvalds | Linus     | 31   |
| Raymond  | Eric      | 40   |
+----------+-----------+------+
3 rows in set (0.00 sec)

mysql> UPDATE age information SET age = 47
    -> WHERE lastname = ´Wall´;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> SELECT * FROM age information;
+----------+-----------+------+
| lastname | firstname | age  |
+----------+-----------+------+
| Wall     | Larry     | 47   |
| Torvalds | Linus     | 31   |
| Raymond  | Eric      | 40   |
+----------+-----------+------+
3 rows in set (0.00 sec)

Be sure to use that WHERE clause; otherwise, if we had only entered UPDATE age information SET age = 47, all the records in the database would have been given the age of 47!

Although this might be good news for some people in these records (how often have the old-timers said "Oh, to be 47 years old again"—OK, probably not), it might be shocking news to others.

This method works, but it requires the database to know that Larry is 46, turning 47. Instead of keeping track of this, for Larry's next birthday we simply increment his age:

mysql> SELECT * FROM age information;
+----------+-----------+------+
| lastname | firstname | age  |
+----------+-----------+------+
| Wall     | Larry     | 47   |
| Torvalds | Linus     | 31   |
| Raymond  | Eric      | 40   |
+----------+-----------+------+
3 rows in set (0.00 sec)

mysql> UPDATE age information SET age = age + 1
    -> WHERE lastname = ´Wall´;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> SELECT * FROM age information;
+----------+-----------+------+
| lastname | firstname | age  |
+----------+-----------+------+
| Wall     | Larry     | 48   |
| Torvalds | Linus     | 31   |
| Raymond  | Eric      | 40   |
+----------+-----------+------+
3 rows in set (0.00 sec)

5.2.8 The DELETE Command

Sometimes we need to delete a record from the table (don't assume the worst—perhaps the person just asked to be removed from a mailing list, which was opt-in in the first place, of course). This is done with the DELETE command:

mysql> DELETE FROM age information WHERE lastname = ´Raymond´;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM age information;
+----------+-----------+------+
| lastname | firstname | age  |
+----------+-----------+------+
| Wall     | Larry     | 48   |
| Torvalds | Linus     | 31   |
+----------+-----------+------+
2 rows in set (0.00 sec)

Eric is in good company here, so put him back:

mysql> INSERT INTO age information
    -> (lastname, firstname, age)
    -> VALUES (´Raymond´, ´Eric´, 40);

Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM age information;
+----------+-----------+------+
| lastname | firstname | age  |
+----------+-----------+------+
| Wall     | Larry     | 48   |
| Torvalds | Linus     | 31   |
| Raymond  | Eric      | 40   |
+----------+-----------+------+
3 rows in set (0.00 sec)

5.2.9 Some Administrative Details

All these examples have been executed as the root MySQL user, which, as you might imagine, is not optimal from a security standpoint. A better practice is to create a MySQL user who can create and update tables as needed.

First, as a security measure, change the MySQL root password when logging in to the server:

# mysqladmin password IAmGod

Now when mysql executes, a password must be provided using the -pswitch. Here is what would happen if we forgot the -p:

$ mysql -u root
ERROR 1045: Access denied for user: ´root@localhost´ (Using password: NO)

Try again using -p. When prompted for the password, enter the one given previously:

Recall that the MySQL user is not the same as a Linux user. The mysqladmin command changes the password for the MySQL user only, not the Linux user. For security reasons, we suggest that the MySQL password never be the same as the password used to log in to the Linux machine. Also, the password IAmGod, which is clever, is a bad password for many reasons, including the fact that it is used as an example in this book. For a discussion on what makes a password good or bad, we suggest you read Hacking Linux Exposed [Hatch+ 02].

$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 15 to server version: 3.23.36

Type ´help;´ or ´\h´ for help. Type ´\c´ to clear the buffer
mysql>

Doing all the SQL queries in the people database as the MySQL root user is a Bad Idea (see HLE if you want proof of this). So let's create a new user. This involves modifying the database named mysql, which contains all the administrative information for the MySQL server, so first we use the mysql database and then grant privileges for a new user:

mysql> USE mysql;
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> GRANT SELECT,INSERT,UPDATE,DELETE
    -> ON people.*
    -> TO apache@localhost
    -> IDENTIFIED BY ´LampIsCool´;
Query OK, 0 rows affected (0.00 sec)

The user apache (the same user that runs the webserver) is being granted the ability to do most everything within the database, including being able to delete entries in tables within the people database. However, apache cannot delete the people database, only entries within the tables in the database. The user apache can access the people database from localhost only (instead of being able to log in over the network from another machine).

The IDENTIFIED BY clause in the SQL command sets the apache user's password to LampIsCool. Setting the password is necessary only the first time permissions are granted for this user—later, when the apache user is given permissions in other databases, the password doesn't need to be reset.

To verify that these changes were made, log in as apache:

$ mysql -u apache -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 27 to server version: 3.23.36

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

mysql> USE people
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> SHOW TABLES;
+------------------+
| Tables_in_people |
+------------------+
| age_information  |
+------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM age information;
+----------+-----------+------+
| lastname | firstname | age  |
+----------+-----------+------+
| Wall     | Larry     | 48   |
| Torvalds | Linus     | 31   |
| Raymond  | Eric      | 40   |
+----------+-----------+------+
3 rows in set (0.00 sec)

5.2.10 Summary

As discussed, these commands are enough to do basic things with MySQL:

SHOW DATABASES
CREATE DATABASE
USE
CREATE TABLE
SHOW TABLES
DESCRIBE
INSERT
SELECT
UPDATE
DELETE
GRANT

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020