Lecture6 MYSQL

download Lecture6 MYSQL

of 48

Transcript of Lecture6 MYSQL

  • 8/7/2019 Lecture6 MYSQL

    1/48

    Hdip Software ProjectMySQL and Database Connectivity through

    Java

    Dr Martina NaughtonRoom: A1.15

    E-mail: [email protected]

  • 8/7/2019 Lecture6 MYSQL

    2/48

    Databases Topics covered this

    week

    Aims:

    MySQL - Intro to the SQL query language

    Jdbc connectivity - how to manipulate your

    database through Java (JavaBeans/JSPs)

  • 8/7/2019 Lecture6 MYSQL

    3/48

    Part 1: MySQL

    About MySQL

    Connecting to MySQL

    Overview of basic commands

    Inserting data

    Selecting certain entries

    Altering existing entries Deleting data

  • 8/7/2019 Lecture6 MYSQL

    4/48

    Database: recap

    A Database is simply a collection of data. In relationaldatabase, data is organized into tables.

    Database Management System (DBMS) is software tomaintain and utilize the collections of data (e.g., Oracle,DB2, MySQL)

    Students Table

    MCCarthyBary3

    BloggsJoe2

    NaughtonMartina1

    last_namefirst_namestudent_id

  • 8/7/2019 Lecture6 MYSQL

    5/48

    About MySQL

    MySQL = Free open source SQL (StructuredQuery Language) database server.

    SQL language defines how to insert, retrieve,modify and delete data

    Your BEST Friend:

    MySQL 5.0 ReferenceManual

    http://dev.mysql.com/doc/refman/5.0/en/index.html

  • 8/7/2019 Lecture6 MYSQL

    6/48

    Connecting to MySQL

    Use mysql on csserver.ucd.ie

    Everyone have been granted:

    An account on csserver Username = FirstName_initial + Surname

    E.g., Martina Naughton = mnaughton

    Password = randomly generated (will be handed out after lecture)

    A MySQL account Username = same as above

    Password = same as above

  • 8/7/2019 Lecture6 MYSQL

    7/48

    Connecting to

    csserver.ucd.ie Mac/Linux: open a terminal window and login

    using:

    ssh [email protected] Windows: download putty connection manager

    Download the putty from:http://the.earth.li/~sgtatham/putty/latest/x86/putty.exeand save it on your desktop.

    When you double click on putty, you will get thefollowing:

  • 8/7/2019 Lecture6 MYSQL

    8/48

    Putty -- Connection Manager

    1. Entercsserver.ucd.ie as the host name 2. Select SSH

    3. Click Open

  • 8/7/2019 Lecture6 MYSQL

    9/48

    Start mysql by typing the following command: mysql -u username -p

    You give your username with -u, and the -p optiontells MySQL to prompt you for a password.

    You will be prompted for your password - Remember: this is the same password as the one you use

    to log into yourcsserver.ucd.ie account.

    Connecting to MySQL

  • 8/7/2019 Lecture6 MYSQL

    10/48

    If everything is successful, you should see aMySQL command prompt that looks like this:

    Connecting to MySQL contd

    Welcome to the MySQL monitor. Commands end with ; or \g.

    Your MySQL connection id is 688

    Server version: 5.0.77-log Source distribution

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

    buffer.

    mysql>

    The version ofMySQL that you are using

  • 8/7/2019 Lecture6 MYSQL

    11/48

    Creating a Database

    On csserver.ucd.ie, each user haspermission to create one database. This feature is unique to

    csserver(administrators

    choice)

    All the tables you create will be put in here.

    The name of the database MUST be the same asyour username forcsserver.ucd.ie. Again, this feature is unique to csserver

  • 8/7/2019 Lecture6 MYSQL

    12/48

    Creating a Database contd

    To create your database, type the following command at theMySQL command prompt:

    mysql> CREATE DATABASE database_name;

    You can now specify that this is the database that you wantto operate on with this command:

    mysql> USE username;

    Any other commands you give will now be run on thisdatabase.

    NB: Dont forget semi-colons!

  • 8/7/2019 Lecture6 MYSQL

    13/48

    Creating Tables

    Inside your database, you will need anumber of tables to hold your data.

    Following slide contains a command tocreate tables to hold information aboutstudents.

    for this simple example, we're only going tostore their first and last names

  • 8/7/2019 Lecture6 MYSQL

    14/48

    Student Example

    mysql> CREATE TABLE students (

    student_id INT PRIMARY KEY AUTO_INCREMENT,

    first_name VARCHAR(30),

    last_name VARCHAR(30)

    );

  • 8/7/2019 Lecture6 MYSQL

    15/48

    Student Example contd

    mysql> CREATE TABLE students (

    student_id INT PRIMARY KEY AUTO_INCREMENT,

    first_name VARCHAR(30),

    last_name VARCHAR(30)

    );

    CREATE TABLE is the name of the command we're trying to run.

  • 8/7/2019 Lecture6 MYSQL

    16/48

    Student Example contd

    mysql> CREATE TABLE students (

    student_id INT PRIMARY KEY AUTO_INCREMENT,

    first_name VARCHAR(30),

    last_name VARCHAR(30)

    );

    Every table must have a primary key - indicated by PRIMARY KEY

  • 8/7/2019 Lecture6 MYSQL

    17/48

    Student Example contd

    mysql> CREATE TABLE students (

    student_id INT PRIMARY KEY AUTO_INCREMENT,

    first_name VARCHAR(30),

    last_name VARCHAR(30)

    );

    AUTO_INCREMENT - useful feature for ids that are numbers

    If a student is entered into the database with no id number,

    MySQL will automatically give them a student_id that is

    one greater than the last student to be put in.

  • 8/7/2019 Lecture6 MYSQL

    18/48

    Student Example contd

    mysql> CREATE TABLE students (

    student_id INT PRIMARY KEY AUTO_INCREMENT,

    first_name VARCHAR(30),

    last_name VARCHAR(30)

    );

    Names of the fields that the table should have

  • 8/7/2019 Lecture6 MYSQL

    19/48

    Student Example contd

    mysql> CREATE TABLE students (

    student_id INT PRIMARY KEY AUTO_INCREMENT,

    first_name VARCHAR(30),

    last_name VARCHAR(30)

    );

    mysql> CREATE TABLE students (

    student_id INT PRIMARY KEY AUTO_INCREMENT,

    first_name VARCHAR(30),

    last_name VARCHAR(30)

    );

    The INT datatype indicates that the student_id must be an integer.

    VARCHAR(30) says that first_name and last_name are

    variable-length strings of characters.

    The (30) refers to the maximum length that any first_name or

    last_name can be.

  • 8/7/2019 Lecture6 MYSQL

    20/48

    More on creating tables

    A database can hold multiple tables

    Lets also create another table in the same way, to hold

    info about grades

    mysql> CREATE TABLE grades (student_id INT,

    class_id INT, grade FLOAT, PRIMARY KEY(student_id,

    class_id));

  • 8/7/2019 Lecture6 MYSQL

    21/48

    More on creating tables

    A database can hold multiple tables

    Lets also create another table in the same way,

    to hold info about grades

    mysql> CREATE TABLE grades (student_id INT,

    class_id INT, grade FLOAT, PRIMARY KEY(student_id,

    class_id));

    NOTE: difference in how primary key is defined here

  • 8/7/2019 Lecture6 MYSQL

    22/48

    Finding out info about your

    database Two useful commands

    SHOW TABLES command will give you the names ofall the tables that are currently present in your database.

    mysql> show tables;+---------------------+

    | Tables_in_mnaughton |

    +---------------------+

    | classes |

    | grades |

    | students |

    +---------------------+

    3 rows in set (0.00 sec)

  • 8/7/2019 Lecture6 MYSQL

    23/48

    Finding out info about your

    database contd

    Two useful commands

    To find out more about the fields in a particular table,

    use the DESCRIBE command. This will show the fieldsin your table, the datatypes, primary keys, etc.

    Syntax: mysql> DESCRIBE table_name;

    mysql> DESCRIBE students;

    +------------+-------------+------+-----+---------+----------------+

    | Field | Type | Null | Key | Default | Extra |+------------+-------------+------+-----+---------+----------------+

    | student_id | int(11) | NO | PRI | NULL | auto_increment |

    | first_name | varchar(30) | YES | | NULL | |

    | last_name | varchar(30) | YES | | NULL | |

    +------------+-------------+------+-----+---------+----------------+3 rows in set (0.00 sec)

  • 8/7/2019 Lecture6 MYSQL

    24/48

    Finding out info about your

    database contd This command (DESCRIBE) is particularly

    important when you want to insert orloaddata into your database.

    For these commands, it is necessary to know whatorder the fields should be in.

    For the student table above, the first should bestudent_id, followed by first_name andfinally last_name.

  • 8/7/2019 Lecture6 MYSQL

    25/48

    Loading data into your database

    Many ways to achieve this

    Load from a data file

    Insert data one entry/item at a time

    This is more than likely what you will be doing

    i.e. take data from a webform and enter it into the

    database via java program, one item at a time (an

    example will follow in later slides)

  • 8/7/2019 Lecture6 MYSQL

    26/48

    Loading from a file

    Instead of writing an SQL statement to insert eachitem into your database, you can instead create atab-delimited file.

    Each file should have one record per line, with thefields on each line delimited by a tab character.

    The fields should be in the same order as they arein your table definition.

  • 8/7/2019 Lecture6 MYSQL

    27/48

    Example File: Students.txt

    1 Martina Naughton

    2 Tina Woods

    3 Bary MCCarthy4 Jeff Phelan

    5 Marcus Alvers

    6 Michael Amadore

    7 Carl Gaffney

    8 Rachel Mooney

    9 Lisa Fowler

    10 AugustMakalakalane

    A separates each field

  • 8/7/2019 Lecture6 MYSQL

    28/48

    Loading Data from a file

    Use LOAD DATA INFILE command

    More info available at:http://dev.mysql.com/doc/refman/5.0/en/load-data.html

    Example:mysql> LOAD DATA LOCAL INFILE 'students.txt'INTO TABLE students;

    Expected Output:Query OK, 10 rows affected (0.00 sec)

    Records: 10 Deleted: 0 Skipped: 0 Warnings: 0

  • 8/7/2019 Lecture6 MYSQL

    29/48

    Entering data one item at a

    time Use INSERT command

    See http://dev.mysql.com/doc/refman/5.0/en/insert.html for moreinformation

    Syntax: INSERT INTO table_name (field_name1,field_name2) VALUES(val1,val2,val3);

    Examples:insert into students (student_id, first_name,

    last_name) values (1, "Martina", "Naughton");

    ORinsert into students (student_id, first_name,

    last_name) values (null, joe", Bloggs");

    If the field is set to be AUTO_INCREMENT - mysql will assign appropriate value

  • 8/7/2019 Lecture6 MYSQL

    30/48

    Selecting data

    Use SELECT statement - possibly the mostcomplex you'll come across

    More information available at:http://dev.mysql.com/doc/refman/5.0/en/select.html

    This is the command you need to fetch data

    from your database.

  • 8/7/2019 Lecture6 MYSQL

    31/48

    Selecting Data contd

    First, a simple example - selecting everything froma table (students table):

    mysql> SELECT * FROM students;

    Your response should look something like:+------------+------------+-----------+

    | student_id | first_name | last_name |

    +------------+------------+-----------+

    | 1 | Martina | Naughton |

    | 2 | Joe | Bloggs |

    +------------+------------+-----------+

    The * indicates that you want all the fields in the table to be selected.

  • 8/7/2019 Lecture6 MYSQL

    32/48

    Selecting Data contd

    You could also specify particular fields if youdidn't want everything to be selected:mysql> SELECT first_name, last_name FROM students;

    Your response should look something like:+------------+-----------+

    | first_name | last_name |

    +------------+-----------+

    | Martina | Naughton |

    | Joe | Bloggs |

    +------------+-----------+

    2 rows in set (0.00 sec)

  • 8/7/2019 Lecture6 MYSQL

    33/48

    Selecting Data contd

    By default, the specified rows will be selected from

    every row in your table.

    Adding a WHERE clause to your statement cancause only particular rows to be selected:mysql> SELECT * FROM students WHERE student_id=2;

    +------------+------------+-----------+

    | student_id | first_name | last_name |+------------+------------+-----------+

    | 2 | Joe | Bloggs |

    +------------+------------+-----------+

    1 row in set (0.00 sec)

  • 8/7/2019 Lecture6 MYSQL

    34/48

    Selecting Data contd

    You may get a result list such as:+------------+--------------+

    | first_name | last_name |

    +------------+--------------+| Martina | Naughton |

    | Marcus | Alvers |

    | Marcus | Alvers |

    | Michael | Amadore |

    | Rachel | Mooney |

    | August | Makalakalane || August | Makalakalane |

    +------------+--------------+

    To remove duplicates, use select distinct from instead ofselect from

    Duplicates]

  • 8/7/2019 Lecture6 MYSQL

    35/48

    Selecting Data contd

    You can also set a limit to the number of recordsthat should be selected.

    For example, to select the first 5 records in thestudents table:mysql> SELECT * FROM students LIMIT 5;+------------+------------+-----------+

    | student_id | first_name | last_name |

    +------------+------------+-----------+

    | 1 | Martina | Naughton |

    | 2 | Joe | Bloggs |

    | 3 | Bary | MCCarthy |

    | 4 | Jeff | Phelan |

    | 5 | Marcus | Alvers |

    +------------+------------+-----------+

  • 8/7/2019 Lecture6 MYSQL

    36/48

    Selecting Data contd

    You can also control the order in which the recordsare returned.

    For example, in ascending order by last name:mysql> SELECT * FROM students order by last_name ASC

    LIMIT 5;

    +------------+------------+-----------+

    | student_id | first_name | last_name |

    +------------+------------+-----------+

    | 5 | Marcus | Alvers |

    | 6 | Michael | Amadore |

    | 2 | Joe | Bloggs |

    | 9 | Lisa | Fowler |

    | 7 | Carl | Gaffney |

    +------------+------------+-----------+

  • 8/7/2019 Lecture6 MYSQL

    37/48

  • 8/7/2019 Lecture6 MYSQL

    38/48

    More complex SELECT

    queries

    For more complex queries, you'll have to

    JOIN tables together to get what you're

    looking for You'll find the relevant part of the manual here:

    http://dev.mysql.com/doc/refman/5.0/en/join.html

  • 8/7/2019 Lecture6 MYSQL

    39/48

    Join Example

    Example - to get all the grades relating to aparticular student, you could use the join clause asfollows:mysql> SELECT * FROM students JOIN grades

    USING(student_id) WHERE student_id=1;

    A couple of points to note on this:

    The JOIN we use here causes every row in the studentstable to be linked with every row in the grades table

    where the student_id values are the same. The WHERE clause says that we're only interested in

    the student with a student_id of 1.

  • 8/7/2019 Lecture6 MYSQL

    40/48

    Join Example contd

    Expected output:+------------+------------+-----------+------------+----------+-------+

    | student_id | first_name | last_name | student_id | class_id | grade |

    +------------+------------+-----------+------------+----------+-------+| 1 | John | Falkner | 1 | 1 | 25.5 |

    | 1 | John | Falkner | 1 | 2 | 74.2 |

    +------------+------------+-----------+------------+----------+-------+

    2 rows in set (0.01 sec)

  • 8/7/2019 Lecture6 MYSQL

    41/48

    Updating Data

    Updating data basically means changing

    data that's already in the database.

    This is done with the UPDATE command

    More information available at:http://dev.mysql.com/doc/refman/5.0/en/update.html

  • 8/7/2019 Lecture6 MYSQL

    42/48

    Updating Data contd

    For example, we need to change some of thenames of the students in our class. Suppose we'vebeen notified that "Carl Gaffney" spells his name

    with a "K".mysql> UPDATE students SET first_name='Karl'WHERE student_id=7;

    Multiple fields can be changed at the same time

    too. From our data, it looks as if Barry McCarthy'sname was typed in a hurry. To correct it:mysql> UPDATE students SET first_name='Barry',last_name='McCarthy' WHERE student_id=3;

  • 8/7/2019 Lecture6 MYSQL

    43/48

    Updating Data contd

    In these examples, we have used the primarykey to identify students that should be

    updated, so only one student's information ata time is being changed.

    However you should note that any student

    that matches the WHERE clause will havetheir data changed.

  • 8/7/2019 Lecture6 MYSQL

    44/48

    Deleting Data

    Deletion of data from a table is done with

    the DELETE command

    More information available at:http://dev.mysql.com/doc/refman/5.0/en/delete.html

    For example, to delete a student with the

    student id "15", we would use this:

    mysql> DELETE FROM students WHERE student_id=15;

  • 8/7/2019 Lecture6 MYSQL

    45/48

    Deleting Data contd

    The DELETE command can delete more than one

    record at a time, so care is needed. Any record that

    matches the WHERE clause will be deleted. Supposing the repeat exams are coming up, so we

    want to replace all fail grades with the grade

    students got in their repeats. Deleting all grades

    under 40% can be done like so:

    mysql> DELETE FROM grades WHERE grade

  • 8/7/2019 Lecture6 MYSQL

    46/48

    Deleting Data contd

    You can also delete all the data in a table reallyeasy (so be careful!) with the following commands:mysql> DELETE FROM students;

    Deletes all entries from students table

    mysql> DELETE FROM grades;

    Deletes all entries from grades table

    mysql> DELETE FROM classes;

    Deletes all entries from classes table

  • 8/7/2019 Lecture6 MYSQL

    47/48

    The End for today

  • 8/7/2019 Lecture6 MYSQL

    48/48

    Part 2: Manipulating your databasethrough Java (JavaBeans/JSPs)

    Cover on Wednesday..