Reference Card MySql
Reference Card MySql
CONTENTS INCLUDE:
n
Configuration Storage Engines Data Types MySQLs Many Clients Key Administration Tasks Hot Tips and more...
Essential MySQL
By W. Jason Gilmore
MySQL comes bundled with several my.cnf templates, each geared towards a specific purpose and resource availability. You can find these files in the support-files directory found in MySQLs installation directory.
ABOUT MYSQL
MySQL is the worlds most popular open source database, sporting a barrier of entry low enough to attract novice developers yet powerful enough to power some of the worlds most popular websites, among them Yahoo!, BBC News, the U.S. Census Bureau, and Craigslist. This reference card was created to help you quickly navigate some of MySQLs most popular features. Covering topics such as configuration, administration software, backup procedures, SQL features, and user management, this card will serve as a handy desk reference for countless projects to come.
FYI
CONFIGURATION
MySQL supports over 260 configuration parameters, capable of controlling behavior regarding memory, logging, error reporting, and much more. While its possible to tweak these parameters by passing them as flags when starting the MySQL server, typically youll want to ensure theyre always set at server startup, done by adding them to the my.cnf file.
www.dzone.com
STORAGE ENGINES
Storage Engine ARCHIVE Description The ARCHIVE engine is optimized for managing large amounts of data designated as stored for archived purposes. Data stored using the ARCHIVE engine can only be inserted and selected, and not deleted nor modified. The Berkeley DB (BDB) storage engine was the first MySQL engine to support transactional operations, but was removed in the version 5.1 release
BDB
~/.my.cnf
Essential MySQL
The my.cnf file is a text file broken into several sections. Each section defines the context of the parameters defined within, the context being specific to a particular MySQL client (see the later section MySQLs Many Clients). For example: # All clients [client] port = 3306 # The mysql client [mysql] safe-updates # The mysqldump client [mysqldump] quick
DZone, Inc.
|
Authoritative content Designed for developers Written by top experts Latest tools & technologies Hot tips & examples Bonus content online New issue every 1-2 weeks
2
tech facts at your fingertips
Essential MySQL
CSV
EXAMPLE
Falcon
FEDERATED
String Types
Type BINARY BLOB / LONGBLOB / MEDIUMBLOB / TINYBLOB CHAR Description The BINARY type stores up to 255 bytes, and operates identically to CHAR except that its used for binary strings. The BLOB, MEDIUMBLOB, TINYBLOB, and LONGBLOB types are used to store data such as images or binary files, and store up to 65,545.
InnoDB
The CHAR type stores between 0 and 255 characters. Any column defined as a CHAR will consume all of the allotted space regardless of the stored string size. For instance, any CHAR column defined as CHAR(25) will require the same amount of space (that required to store 25 characters) no matter the size of the stored string. The ENUM type restricts the stored value to one of several predefined strings. Up to 65,535 elements can be predefined. Allowable values also include and NULL. A SET type operates like an ENUM, although its predefined number of elements tops out at 64. Further, a SET can store zero, one, or multiple values The TEXT, LONGTEXT, MEDIUM, and TINYTEXT types store up to 65,534, 4,294,967,295, 16,777,215, and 255 characters, respectively.
ENUM
MyISAM
DATA TYPES
MySQL supports a rich set of data types capable of representing nearly every conceivable data format, ranging across dates and times, currency, strings, integers, and floats. This section defines each type and its respective range.
The VARBINARY type stores up to 65,535 bytes, and operates identically to VARCHAR except that its used for binary strings. The VARCHAR type stores up to 65,535 characters. Unlike CHAR, each VARCHAR instance requires only the space required to store the provided string, plus one or two additional bytes depending on the string length.
VARCHAR
TIME TIMESTAMP
YEAR
Hot Tip
MySQL is fairly flexible in terms of how it accepts date and time type values. For instance, DATE, DATETIME, and TIMESTAMP will all accept '2008-09-02', '2008/09/02', and '2008*09*02' as valid date values.
DZone, Inc.
|
www.dzone.com
3
tech facts at your fingertips
Essential MySQL
Databases
Creating a Database Once logged into the MySQL server, you can create a new database using the CREATE DATABASE command:
mysql>CREATE DATABASE dzone;
You can also create a new database without logging into the server per se using the mysqladmin client:
%>mysqladmin -u root -p create dzone
Switching to a Database
You can begin using a specific database by specifying it on the commandline when logging into the MySQL server (see Logging into the MySQL server), or by using the USE command:
mysql>USE dzone;
Deleting a Database
Tables
Creating a Table To create a table, pass the desired table name to the CREATE TABLE structure, along with any column definitions:
CREATE TABLE table_name ( column1 definition, column2 definition, ... columnN definition );
For instance:
CREATE TABLE authors ( id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL );
mysql>DESCRIBE table_name;
To view a list of all tables in a database, execute the SHOW TABLES command:
mysql>SHOW TABLES;
To view a list of tables residing in a database other than the one youre currently in, use:
mysql>SHOW TABLES FROM database_name;
Once logged in, you can select a database or begin carrying out other administrative tasks. To save some time you can pass the desired database along on the command line when logging in:
%>mysql -u username -p database_name
You can add, delete and modify table columns using the ALTER TABLE command.
n
If youre connecting to a remote database, pass the hostname or IP address along using the -h option:
%>mysql -h hostname -u username -p database_name
As an example, to add a column to the end of the previously created authors table:
To add a column at a specific location, use the AFTER clause. For instance:
mysql>ALTER TABLE authors ADD COLUMN telephone ->VARCHAR(20) NOT NULL AFTER name;
n
Modifying the mysql Prompt MySQLs default prompt is enough to remind you youre currently logged into MySQL rather than into an operating system shell. However like most shells you can modify MySQLs prompt to your liking. For instance, when logged into the mysql client execute the following command to change your prompt to mysql (user@host)>:
mysql>prompt mysql (\U)> mysql (root@localhost)>
To rename a table, use the ALTER TABLE command with the RENAME clause:
mysql>ALTER TABLE table_name RENAME new_table_name;
DZone, Inc.
www.dzone.com
4
tech facts at your fingertips
Essential MySQL
MANAGING USERS
MySQL is packaged with a powerful security model, capable of controlling practically every conceivable user action, ranging from which commands he can execute to how many queries he can execute in an hour. This model works in a two-step sequence:
Step 1 Authentication Step 2 Authorization The users host, username, and password are examined. If a match is made within MySQLs privilege tables, the user is authorized. Otherwise, the users connection attempt is denied. Once authenticated, the users submitted command is examined and compared against the users defined privileges, also found in MySQLs privilege tables. If the user has sufficient privileges, the command is executed, otherwise it is denied.
However, security-minded administrators can prevent users from potentially modifying or selecting any column but the hours column found in the timesheets table:
mysql>GRANT INSERT (hours), SELECT (hours) ON dzone.timesheets ->TO 'jason'@'192.168.1.145';
Renaming Users To rename an existing user, use the RENAME USER command:
mysql>RENAME USER 'jason'@'192.168.1.145' TO 'wjg'@'192.168.1.145';
Although covering the nuances surrounding MySQLs privilege tables is beyond the scope of this document, the remainder of this section should give you ample reminders regarding commonplace tasks. You are, however, encouraged to carefully review the privilege table documentation found in the MySQL manual (http://dev.mysql.com/doc/), as its easy to make a mistake when using this powerful feature.
Creating a New User Account New user accounts can be created in a variety of ways, however the easiest and most error-proof is through the GRANT command. The general structure looks like this:
mysql>GRANT privilege1, privilege2, privilegeN ON database_name.* ->TO 'username'@'host' IDENTIFIED BY 'password';
Stored Routines
MySQL collectively refers to stored procedures and stored functions as stored routines. Stored procedures are executed using the CALL statement, and can return values as MySQL variables, whereas stored functions can be called directly from within a MySQL like any other standard MySQL function. In this section a brief refresher is provided regarding managing what is arguably the more useful of the two, namely stored functions. Creating a Stored Function A stored function is created using the CREATE FUNCTION command. A simple example follows:
mysql>DELIMITER $$ mysql>CREATE FUNCTION calculate_bonus ->(employee_id INTEGER) RETURNS DECIMAL(5,2) ->BEGIN ->DECLARE article_count INTEGER; ->DECLARE bonus DECIMAL(10,2); ->SELECT count(id) AS article_count FROM articles ->WHERE author_id = employee_id; ->SET bonus = article_count * 10; ->RETURN bonus; ->END; ->$$ mysql>DELIMITER ;
The following command will create a new user named jason, granting SELECT, INSERT, and UPDATE privileges to all tables found in the dzone database when connecting from 192.168.1.145 and when providing the password secret:
mysql>GRANT SELECT, INSERT, UPDATE ON dzone.* ->TO 'jason'@'192.168.1.145' IDENTIFIED BY 'secret';
To grant a user all privileges on all databases, use *.* in place of the database name.
Hot Tip
Be sure to include the IDENTIFIED BY clause when creating new users! Neglecting to include this information results in a user being created without a required password.
Deleting a User Account You can delete a user using two methods, the method you choose being dependent on the context of "delete". To remove all user privileges but not entirely remove the user from the system (for instance if you needed to temporarily disable account access), use the REVOKE command:
mysql>REVOKE ALL PRIVILEGES FROM 'jason'@'192.168.1.145';
To completely remove a user from the system, revoking all privileges and erasing the user account, use the DROP USER command:
mysql>DROP USER 'jason'@'192.168.1.145';
Changing a Password To change a users password, use the SET PASSWORD command. For instance, to change the password of the previously created jason account:
mysql>SET PASSWORD FOR 'jason'@'192.168.1.145' = PASSWORD('supersecret');
Hot Tip
Stored procedures and functions support complex logical syntax features, including conditionals and looping statements.
Granting Privileges To grant additional privileges, you use the GRANT command in precisely the same manner as it was used to create a user; MySQL will recognize the users existence and just modify the users privileges accordingly. For instance, to add the DELETE privilege to the previously created user [email protected]:
mysql>GRANT DELETE ON dzone.* TO 'jason'@'192.168.1.145';
Altering a Stored Function To modify an existing function, use the ALTER FUNCTION command:
mysql>DELIMITER $$ mysql>ALTER FUNCTION calculate_bonus ->MODIFIED FUNCTION BODY... ->$$ mysql>DELIMITER $$
Revoking Privileges To revoke privileges, use the REVOKE command. For instance, to remove the DELETE and UPDATE privileges from the previously created user [email protected]:
mysql>REVOKE DELETE, UPDATE FROM 'jason'@'192.168.1.145';
Deleting a Stored Function To delete a stored function, use the DROP FUNCTION command:
mysql>DROP FUNCTION calculate_bonus;
DZone, Inc.
www.dzone.com
5
tech facts at your fingertips
Essential MySQL
command (only a read lock is required), followed by FLUSH TABLES. Once executed, copy the files, and when the copy is complete, execute UNLOCK TABLES.
Using mysqldump
The mysqldump client is convenient because it supports creating backups of all databases using any MySQL storage engine, not to mention that it automatically takes care of important details such as locking the tables during the backup. The mysqldump client supports an enormous number of options, and its recommended you take some time to review them in the MySQL manual, however this section will give you enough to at least remind you of whats required to perform a variety of different backups.
Passing Query Parameters You can pass parameters to a view like you would any typical query. For instance to retrieve only information about the author with the e-mail address [email protected]:
mysql>SELECT * FROM author_view WHERE email = "[email protected]";
Viewing a View You can examine the columns retrieved by the view using the DESCRIBE statement:
mysql>DESCRIBE author_view;
Of course, youll require proper permissions to execute mysqldump in conjunction with a specific database (namely the SELECT and LOCK privileges), therefore youll typically also need to pass along your username and password. In this case, this command typically looks similar to:
%>mysqldump -u root -p database_name > backup0903.sql
Triggers
Triggers are automatically activated in accordance with a specific table-related event. Theyre useful for automating table updates which should occur when another table is modified in some way.
Creating a Trigger To create a trigger, use the CREATE TRIGGER command, passing the trigger actions into the command body. For instance, the following trigger will increment an categorys article counter each time a new article of that specific category is added to the database:
mysql>DELIMITER $$ mysql>CREATE TRIGGER article_counter ->AFTER INSERT ON articles ->FOR EACH ROW BEGIN ->UPDATE categories SET counter = counter + 1 WHERE id = NEW.category_id; ->END; ->$$ mysql>DELIMITER ;
Using mysqlhotcopy
If all of your backup tables use the MyISAM storage engine, and youre able to log into the server where the tables are stored, the mysqlhotcopy might be the ideal solution due to its speed advantages. To backup the dzone database to a directory located at /home/ jason/backups using mysqlhotcopy, execute:
%>mysqlhotcopy -u root -p dzone /home/jason/backups
Modifying a Trigger You currently cannot modify an existing trigger from within the mysql client. Instead, you should delete the existing trigger and create it anew with the desired changes incorporated. Deleting a Trigger To delete a trigger, execute the DROP TRIGGER command:
mysql>DROP TRIGGER pay_author;
PERFORMING BACKUPS
Performing regular backups is an essential part of even the smallest database project. Fortunately MySQL makes this very easy by offering several backup solutions.
Like mysqldump, mysqlhotcopy offers an enormous number of options, so be sure to review the MySQL manual (http://dev. mysql.com/doc/) to learn all thats available.
Copying Files
If your tables use the MyISAM storage engine, you can backup the database simply by copying the files used to store the tables and data. To do so, youll need to first execute the LOCK TABLES
DZone, Inc.
|
MySQLs replication features make it possible to maintain a consistently synchronized version of the live database. Replication is out of the scope of this reference card, but be sure to visit the MySQL documentation (http://dev.mysql.com/doc/) if replication is more suitable to your needs.
Hot Tip
www.dzone.com
6
tech facts at your fingertips
Essential MySQL
Query Select all rows inserted within the last 24 hours Select all rows inserted today Determine the weekday of the most recent entry Calculating the average age of users Calculating the number of days since the last blog post
Function
mysql>SELECT * FROM entries WHERE entry_date > ->UNIX_TIMESTAMP(NOW()) - 86400; mysql>SELECT * FROM entries WHERE date(entry_date) = ->date(NOW()); mysql>SELECT DAYNAME(MAX(entry_date)) AS day FROM entries;
mysql>SELECT AVG(YEAR(CURDATE()) - YEAR(birthdate)) ->(RIGHT(CURDATE(),5) < RIGHT(birthdate,5))) ->AS age FROM users; mysql>SELECT TO_DAYS(NOW()) - TO_DAYS(MAX(entry_date)) ->FROM posts;
mysql>SELECT (TO_DAYS(NOW()) - TO_DAYS(MAX(entry_date))) Calculating the ->/ 7 FROM posts; number of weeks since the last blog post
RECOMMENDED BOOK
Beginning PHP and MySQL, Third Edition is the definitive book on the PHP language and MySQL database. Essentially three books in one, readers are treated to comprehensive introductions of both technologies, in addition to in-depth instruction regarding using these two powerful technologies in unison to build dynamic web sites.
W. Jason Gilmore
Jason Gilmore is founder of W.J. Gilmore, LLC, a Columbus, Ohio-based firm providing web development, consulting, and technical writing services to clientele ranging from publicly traded corporations to small startups. Jason contributes to a number of publications such as Developer.com, Linux Magazine, and TechTarget. Hes cofounder of the CodeMash conference (http://www.codemash.org/), a non-profit organization charged with organizing the annual namesake event. Away from the computer youll find Jason starting more home remodeling projects than he could possibly complete, and checking more books out of the library than he could possibly read.
Publications
n n
Author of Beginning PHP and MySQL, Third Edition (Apress, 2008) Co-author of Beginning PHP and PostgreSQL 8 (Apress, 2007) and
Beginning PHP and Oracle (Apress, 2007)
Web Site
http://www.wjgilmore.com/
BUY NOW
books.dzone.com/books/phpmysql
Available:
JUnit and EasyMock Spring Annotations Core Java Core CSS: Part II PHP Getting Started with JPA JavaServer Faces Core CSS: Part I Struts2 Core .NET Very First Steps in Flex C# Groovy NetBeans IDE 6.1 Java Editor RSS and Atom
FREE
GlassFish Application Server Silverlight 2 IntelliJ IDEA jQuerySelectors Flexible Rails: Flex 3 on Rails 2
Design Patterns
Published June 2008
DZone communities deliver over 4 million pages each month to more than 1.7 million software developers, architects and decision makers. DZone offers something for everyone, including news, tutorials, cheatsheets, blogs, feature articles, source code and more. DZone is a developers dream, says PC Magazine.
9 781934 238301
Version 1.0
Copyright 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Reference: Beginning PHP and MySQL, Jason Gilmore, Apress, 2008.
$7.95