1. Connecting to and Disconnecting from the Server
To connect to the MySQL server, provide the host name (db_host), user name (db_user), and enter the password when prompted. Adjust values based on your setup:
$> mysql -h db_host -u db_user -p
Enter password: ********
After successful connection, to disconnect, use the QUIT command at the MySQL prompt:
mysql> QUIT
Bye
2. Creating and Using Databases
To list existing databases on the server, use:
SHOW DATABASES;
To access an existing database (e.g., test), use:
USE test;
Note: The USE statement does not require a semicolon and can be written on a single line. If you have permissions, create a database (e.g., animal_db) and grant access:
CREATE DATABASE animal_db;
GRANT ALL ON animal_db.* TO 'db_user'@'client_host';
Here, db_user is your MySQL username, and client_host is the host you connect from.
On Unix systems, database and table names are case-sensitive (unlike SQL keywords). Always use consistent casing, e.g., menagerie (not Menagerie or MENAGERIE).
To create a data base named menagerie (adhering to case rules):
mysql> CREATE DATABASE menagerie;
3. Creating a Table
To create a table (e.g., pets) with columns for pet details, use the CREATE TABLE statement. For example:
mysql> CREATE TABLE pets (
name VARCHAR(25),
owner VARCHAR(25),
species VARCHAR(25),
gender CHAR(1),
birth_date DATE,
death_date DATE
);
This table includes fields like:
name: The pet’s name (stored as a string up to 25 characters)owner: The pet’s owner (string, 25 characters max)species: The animal species (e.g., 'dog', 'cat')gender: The pet’s gender (single character, e.g., 'm' or 'f')birth_date: Date of birthdeath_date: Date of death (if applicable)