Você está na página 1de 9

CPSC 421:

Database Management Systems

MySQL Basics
Getting Started
The server
The MySQL Shell
Creating Tables
Loading data
Querying Data
Prepared Statements & Views

Getting Started
MySQL Website
http://www.mysql.com
Download
http://dev.mysql.com
The community server version (free)
I installed version 5.1 (other version avail.)
Almost all platforms supported (OS X, Windows, Linux, )
Binary installers available
Should read installation instructions (if installing on your own)
Documentation
http://dev.mysql.com/doc
Should read about setting up accounts, passwords, etc. in manual
Also, section on database administration is useful
2

1
For this course

Matt Bergman has set up MySQL on ada, windows/linux servers


You can use one of these, install your own version on a personal
machine, or use an entirely different DBMS
If you use the installation at Gonzaga
please send email to Matt to request an account

If you are going to use a different DBMS


let me know which you are planning on using

other options might be PostgreSQL, MonetDB/SQL (also free)

or Oracle, DB2, SQL Server, MS Access* (commercial)

About MySQL

Features
Open-source (GPL)
A Real DBMS (e.g., disk storage depending on storage engine)
Supports much of SQL (99) but not all
Many advanced features, e.g., stored procedures, triggers, views,
Different storage engines, per table
This can be a bit confusing because of different choices
MySQL allows new engines to be created (Pluggable API)
Caching
Replication
Transactions (InnoDB, others)

2
Starting and Stopping the Server

Typical installation
Start the server (see installation instructions)
Run mysql command (e.g., /usr/local/mysql/bin/mysql)
Create accounts, set up passwords and priviledges

Alternatively, you can use the MySQL GUI Tools


http://dev.mysql.com/downloads/gui-tools/
This is a lot easier!
MySQL Administrator for 
doing above and more
MySQL Query Browser for 
creating tables, writing and running 
queries, etc.

MySQL Monitor (client app)


Command line application mysql
$ mysql
$ mysql -u user -p
$ mysql -h host -u user -p

From the monitor, you can: Perform admin, exec. queries,


check system status, etc.
[sbowers:~]$ mysql -u sbowers -p
Enter password:
For  Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 22
example: Server version: 5.0.67 MySQL Community Server (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.00 sec)
mysql> quit
Bye 6
[sbowers:~]$

3
Creating a Database
As root (depending on permissions)
mysql> CREATE DATABASE <dbname>;

Creates a database, and now you can add tables, etc.

To select the database:


mysql> USE <dbname>;

Can start the monitor in the database:


$ mysql -u user -p <dbname>

Can see the tables of the db:


mysql> show tables;

Can also do this via MySQL Query Browser


7

Creating Tables

Can issue SQL statements via the monitor, including create table
mysql> USE mydb
mysql> CREATE TABLE ingredients (id INT, name VARCHAR(30));

Creates a 2-column table

To verify that your table was created:


mysql> DESCRIBE ingredients;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(30) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.08 sec)

To remove the table:


Mysql> DROP TABLE ingredients; 8

4
Creating Tables

The MySQL Query Browser can also be used to create


tables

Creating Tables
MySQL Query Browser exposes more options, e.g., allowing the
storage engine of a table, and much more
InnoDB is (currently) most feature rich (transactions, indices, etc.)
MyISAM is the other major engine

Generates underlying SQL, which


is sent to the server:
CREATE TABLE `mydb`.`ingredients` (
`id` INT,
`name` VARCHAR(30)
)
ENGINE = InnoDB
CHARACTER SET utf8;

10

5
Loading Data
Again, can issue insert command:
mysql> INSERT INTO ingredients VALUES (1, jalapeno);
mysql> INSERT INTO ingredients VALUES (2, habanero);

Can also use the load data command:


mysql> LOAD DATA LOCAL INFILE ~/ingredients.txt INTO TABLE
ingredients;

The data file should be tab-delimitted with each record on a newline. Nulls values are
denoted by \N, e.g.:
1 jalapeno
2 habanero
3 tomatillo
4 \N

Data can be removed using delete command:


mysql> DELTE FROM ingredients WHERE id < 10;
11

Querying Data
Can issue queries directly in monitor:
mysql> SELECT * FROM ingredients;
+------+---------------+
| id | name |
+------+---------------+
| 1 | 'jalapeno' |
| 2 | 'habanero' |
| 3 | 'tomatillo' |
| 4 | 'bell pepper' |
| 5 | 'onion' |
| 6 | 'cayenne' |
| 7 | NULL |
+------+---------------+

As well as from the MySQL 


Query Browser
12

6
Explaining Queries

Can prepend queries with Explain to show information the


query optimizer uses:
mysql> EXPLAIN SELECT * FROM ingredients WHERE id=3 or id=4;
+----+-------------+-------------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | ingredients | ALL | NULL | NULL | NULL | NULL | 7 | Using where |
+----+-------------+-------------+------+---------------+------+---------+------+------+-------------+

Can run Explain through MySQL Query Browser as well

The result is more interesting as queries become more


complicated

13

Prepared Statements
Allow you to assign a name to an SQL query, which typically
contains parameters
Stored on the server and executed by passing parameter values
Here is a simple example:
mysql> PREPARE get_ingredient_name FROM
'select name from ingredients where id=?';
mysql> SET @id = 3;
mysql> EXECUTE get_ingredient_name USING @id;
+-------------+
| name |
+-------------+
| 'tomatillo' |
+-------------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE get_ingredient_name

Often used when building applications that interact with a


database (through a prepared statement API)
14

7
Views
Views provide a way to name a query, and then use that name as
a relation in another query

Here is a simple example:


mysql> CREATE VIEW peppers AS SELECT * FROM ingredients WHERE id
IN(1,2,4,6);

mysql> SELECT * FROM peppers;


+------+---------------+
| id | name |
+------+---------------+
| 1 | 'jalapeno' |
| 2 | 'habanero' |
| 4 | 'bell pepper' |
| 6 | 'cayenne' |
+------+---------------+

15

MySQL in batch mode


Instead of using mysql interactively, you can also use it to run scripts (series
of mysql commands)
For example: 
$ mysql < batch-file

$ mysql -u user -p < batch-file

etc.

You can also load your script via mysql:


mysql> source batchfile

Why use batch files?


Saves typing
Stores your database table defs, views, etc., in case you need to start over
Easy to edit/extend your scripts (e.g., if trying to figure out the right query)
Can create your database on different servers, etc.
Documentation of what you did
Etc.
16

8
Lots more
MySQL has many features we did not discuss
the MySQL documentation is a great resource
some things you might want to look at are:
Transactions
Stored Procedures
How to access MySQL via JDBC
Crash recovery
Storage engines
How to backup your database
Limitations of SQL support, and workarounds (e.g., minus)
Spatial Extensions
Functions and operators
Data types
PHP support

other tools supporting MySQL, e.g., phpMyAdmin (web-based
database administration)
17

Você também pode gostar