SlideShare a Scribd company logo
Introduction to MySQL

●   Introduction
●   Installation
●   SQL
●   Schema design
●   Perl




BITS/VIB Bioinformatics Training – Jun 29, 2011 – Luc Ducazu <luc@daphnia.com>
Database schema
●   Although you can execute DDL commands from 
    the MySQL monitor directly, this is not often 
    done
●   There are tools that allow you to design a schema 
    graphically and generate the CREATE TABLE ... 
    statements 
●   Examples:
    –   MySQL workbench
    –   Dia
MySQL workbench
●   Available as a standard package on some Linux 
    distros (eg Fedora) 
●   Available as Windows MSI, Linux DEB or RPM 
    package or source archive from 
    http://dev.mysql.com/downloads/workbench/
●   To install a DEB package:
    # dpkg ­i package.deb
●   To install a RPM package:
    # rpm ­Uvh package.rpm
MySQL workbench ­ demo
Database schema
●   Once the schema is designed, MySQL workbench 
    can generate a 'script' containing all SQL 
    statements to create the tables and other objects:
    File ­> 
    Export ­> 
    Forward Engineer SQL CREATE Script
●   This 'script' can be executed as usual from the 
    MySQL monitor
Inserting rows
●   To populate tables, use the INSERT SQL 
    statement:
    mysql> insert into tbl
           (col1, col2, ...) 
           values
           (val1, val2, ...) [,
           (valx, valy, ...) , ...]
●   With:
    –   tbl the name of the table
    –   col1, col2, ... a list (subset) of column names
    –   val1 value for col1
    –   val2 value for col2
Inserting rows ­ examples
●   Example (biodb version 1)
    insert into modorg
    (id, class, genus, species,
     nchr, gsize, draft)
    values
    (1, “Bacteria”, “Escherichia”, “coli”,
     1, 4.639, “1997­09­05 00:00:00”)
●   Note that strings and dates have to be properly 
    quoted
Inserting rows
●   You can leave out the column list if
     – a value is given for all columns
     – the values are specified in the order dictated by the 
       schema
    mysql> insert into tbl
           values
           (val1, val2, ...) [,
           (valx, valy, ...) , ...]
Changing rows
●   To change one or more rows, use the UPDATE 
    SQL statement:
    mysql> update tbl
    set col1=expr1 [, col2=expr2, ...]
    [where cond]
●   With:
    –   tbl the name of the table
    –   col1 the column to change
    –   expr1 the new value 
    –   cond the row filter ­ if unspecified, all rows of the 
        table will be updated
Changing rows ­ examples
●   To change the C elegans number of 
    chromosomes to 7:
    update modorg
    set nchr = 7
    where genus = “caenorhabditis”
      and species = “elegans”;
●   To change the draft date to the current date:
    update modorg
    set draft = now();
Deleting rows
●   To remove rows, you use the DELETE SQL 
    statement:
    delete from tbl
    [where cond]
●   With:
    –   tbl the name of the table
    –   cond the row filter ­ if unspecified, all rows of the 
        table will be deleted
    –   note: since you can only remove entire rows, there is 
        no need to specify column names
Deleting rows ­ examples
●   To remove all in model organisms with a genome 
    publishing date before 2000:
    delete from modorg
    where year(draft) < 2000;
Introduction to MySQL

●   Introduction
●   Installation
●   SQL
●   Schema design
●   Perl



BITS/VIB Bioinformatics Training – Jun 29, 2011 – Luc Ducazu <luc@daphnia.com>
Perl
●   Perl is a scripting language that has excellent text 
    manipulation capabilities
●   Many biological 'databases' are available as flat 
    text files
●   Perl is very handy in the automation of the 
    population of MySQL databases
Automated population
●   There are basically two ways Perl can help to 
    insert data into tables:
    –   The Perl script generates USE, INSERT, ... SQL 
        statements. You can than execute these statements 
        using the MySQL monitor:
        $ perl myscript.pl | mysql
    –   The Perl script connects to the database and executes 
        SQL statements directly: DBI
Perl DBI
●   Perl DBI provides a programming interface that 
    abstracts most of the RDBMS specifics
●   In principle it should be possible to port scripts, 
    written for other RDBMS's (like PostgreSQL), to 
    MySQL with only minimal effort: all you have to 
    do is change the connection string
●   Packages to install (Ubuntu)
    –   libdbi­perl: Perl DBI
    –   libdbd­mysql­perl: MySQL driver for DBI
Perl DBI ­ connecting
●   Here is a minimal program:

    #!/usr/bin/perl ­w
    use strict;
    use DBI;

    my $dbh = DBI­>connect(
         “DBI:mysql:host=localhost;database=biodb”,
         “user”,
         “password”) or die;
    ...
    $dbh­>disconnect();
Perl DBI ­ connecting
●   Some highlights:
    –   use DBI;
        Load Perl DBI library
    –   DBI­>connect(connection string);
        Connect to a database
         ●   it is a MySQL database server
         ●   the DB server is running on the local machine
         ●   you can provide the name of the database
         ●   you can provide a user name and password
        The connect() function returns
         ●   a database handle ($dbh) on success
         ●   false on failure
    –   $dbh­>disconnect() to clean up resources
Perl DBI 
●   To execute a SQL statement that does not return a 
    result set, eg INSERT, DELETE, use do():
    my $n = $dbh­>do(stmt);
●   This function
    –   requires a valid database handle
    –   returns the number of rows affected, if no rows are 
        affected, a special value is returned: 0E0 (evaluates 
        true)
    –   false in case of an error
●   You can use execute() as well
Perl DBI 
●   To execute a SQL statement that returns a result 
    set, eg SELECT use the following recipe:
    1. Prepare a statement:
    my $sth = $dbh­>prepare(stmt);
    2. Send the query to the database server:
    $sth­>execute();
    3. Read the result, row by row:
    my @row = $sth­>fetchrow_array();
    my $ref = $sth­>fetchrow_hashref();
    4. Clean up resources:
    $sth­>finish();
Perl DBI ­ examples
●   To list all classes in modorg:
    ...
    my $qry = “select distinct class ”
            . “from modorg ” 
            . “order by class”;
    my $sth = $dbh­>prepare($qry);
    $sth­>execute();
    while(my @row = $sth­>fetchrow_array())
    {
       print “$row[0]n”;
    };
    $sth­>finish();
    ...
Perl DBI ­ examples
●   To list all organisms in modorg:
    ...
    my $qry = “select genus, species ”
            . “from modorg ” 
            . “order by genus”;
    my $sth = $dbh­>prepare($qry);
    $sth­>execute();
    while(my $ref = $sth­>fetchrow_hashref())
    {
       print $ref­>{“genus”} . “ “ 
           . $ref­>{“species”} . “n”;
    };
    $sth­>finish();
    ...
Perl DBI ­ examples
●   To insert a bunch of rows into modorg:
    ...
    my $qry = “insert into modorg ”
            . “(id, class, genus, species) ” 
            . “values (?, ?, ?, ?)”;

    my $sth = $dbh­>prepare($qry);
    $sth­>execute(11, “Mammels”, 
          “Sus”, “scrofa”);
    ...
Quoting
●   Never allow arbitrary user input in SQL 
    statements

More Related Content

PDF
BITS: Introduction to relational databases and MySQL - SQL
PDF
BITS: Introduction to MySQL - Introduction and Installation
PPTX
Introduction databases and MYSQL
PPTX
MySql:Introduction
PPTX
Learn PHP Lacture2
PDF
Lobos Introduction
PPT
BITS: Introduction to relational databases and MySQL - SQL
BITS: Introduction to MySQL - Introduction and Installation
Introduction databases and MYSQL
MySql:Introduction
Learn PHP Lacture2
Lobos Introduction

What's hot (20)

PPT
PHP - Intriduction to MySQL And PHP
PPTX
My sql administration
PDF
Scaling Databases with DBIx::Router
PPTX
Jdbc Java Programming
PDF
Perl Stored Procedures for MySQL (2009)
PPT
MySQL lecture
PDF
Using Perl Stored Procedures for MariaDB
PPT
Mysql Ppt
PDF
External Language Stored Procedures for MySQL
PDF
Los Angeles R users group - Dec 14 2010 - Part 2
PPT
Mysql ppt
PPTX
Introduction to my_sql
PDF
lab56_db
PPTX
PostgreSQL Database Slides
PPTX
Database Connectivity in PHP
PDF
4.3 MySQL + PHP
PPTX
Beginner guide to mysql command line
PDF
Building node.js applications with Database Jones
ODP
Common schema my sql uc 2012
PPT
A brief introduction to PostgreSQL
PHP - Intriduction to MySQL And PHP
My sql administration
Scaling Databases with DBIx::Router
Jdbc Java Programming
Perl Stored Procedures for MySQL (2009)
MySQL lecture
Using Perl Stored Procedures for MariaDB
Mysql Ppt
External Language Stored Procedures for MySQL
Los Angeles R users group - Dec 14 2010 - Part 2
Mysql ppt
Introduction to my_sql
lab56_db
PostgreSQL Database Slides
Database Connectivity in PHP
4.3 MySQL + PHP
Beginner guide to mysql command line
Building node.js applications with Database Jones
Common schema my sql uc 2012
A brief introduction to PostgreSQL
Ad

Viewers also liked (6)

PDF
Relational Database Schema for MPEG 7 Visual Descriptors by Florian
PDF
RNA-seq for DE analysis: extracting counts and QC - part 4
PPT
Eer >r.model
PPT
Er & eer to relational mapping
PPS
Crj 3 1-b
PPT
ER DIAGRAM TO RELATIONAL SCHEMA MAPPING
Relational Database Schema for MPEG 7 Visual Descriptors by Florian
RNA-seq for DE analysis: extracting counts and QC - part 4
Eer >r.model
Er & eer to relational mapping
Crj 3 1-b
ER DIAGRAM TO RELATIONAL SCHEMA MAPPING
Ad

Similar to BITS: Introduction to relational databases and MySQL - Schema design (20)

PPT
Mysql DBI
PPT
My sql with querys
PPT
MySql slides (ppt)
PDF
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
PPT
MySQL Database System Hiep Dinh
PPT
mysqlHiep.ppt
PPTX
Data types and variables in php for writing and databse
PPTX
Lecture3 mysql gui by okello erick
PPT
PDF
PDF
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
PPT
Basic Commands using Structured Query Langauage(SQL)
PPTX
Lecture2 mysql by okello erick
PPT
MySQL and its basic commands
PDF
MySQL for beginners
PPT
Mysql database
PDF
My S Q L Introduction for 1 day training
PDF
My sql introduction for Bestcom
Mysql DBI
My sql with querys
MySql slides (ppt)
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
MySQL Database System Hiep Dinh
mysqlHiep.ppt
Data types and variables in php for writing and databse
Lecture3 mysql gui by okello erick
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
Basic Commands using Structured Query Langauage(SQL)
Lecture2 mysql by okello erick
MySQL and its basic commands
MySQL for beginners
Mysql database
My S Q L Introduction for 1 day training
My sql introduction for Bestcom

More from BITS (20)

PDF
RNA-seq for DE analysis: detecting differential expression - part 5
PDF
RNA-seq for DE analysis: the biology behind observed changes - part 6
PDF
RNA-seq: analysis of raw data and preprocessing - part 2
PDF
RNA-seq: general concept, goal and experimental design - part 1
PDF
RNA-seq: Mapping and quality control - part 3
PDF
Productivity tips - Introduction to linux for bioinformatics
PDF
Text mining on the command line - Introduction to linux for bioinformatics
PDF
The structure of Linux - Introduction to Linux for bioinformatics
PDF
Managing your data - Introduction to Linux for bioinformatics
PDF
Introduction to Linux for bioinformatics
PDF
BITS - Genevestigator to easily access transcriptomics data
PDF
BITS - Comparative genomics: the Contra tool
PDF
BITS - Comparative genomics on the genome level
PDF
BITS - Comparative genomics: gene family analysis
PDF
BITS - Introduction to comparative genomics
PDF
BITS - Protein inference from mass spectrometry data
PDF
BITS - Overview of sequence databases for mass spectrometry data analysis
PDF
BITS - Search engines for mass spec data
PDF
BITS - Introduction to proteomics
PDF
BITS - Introduction to Mass Spec data generation
RNA-seq for DE analysis: detecting differential expression - part 5
RNA-seq for DE analysis: the biology behind observed changes - part 6
RNA-seq: analysis of raw data and preprocessing - part 2
RNA-seq: general concept, goal and experimental design - part 1
RNA-seq: Mapping and quality control - part 3
Productivity tips - Introduction to linux for bioinformatics
Text mining on the command line - Introduction to linux for bioinformatics
The structure of Linux - Introduction to Linux for bioinformatics
Managing your data - Introduction to Linux for bioinformatics
Introduction to Linux for bioinformatics
BITS - Genevestigator to easily access transcriptomics data
BITS - Comparative genomics: the Contra tool
BITS - Comparative genomics on the genome level
BITS - Comparative genomics: gene family analysis
BITS - Introduction to comparative genomics
BITS - Protein inference from mass spectrometry data
BITS - Overview of sequence databases for mass spectrometry data analysis
BITS - Search engines for mass spec data
BITS - Introduction to proteomics
BITS - Introduction to Mass Spec data generation

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
KodekX | Application Modernization Development
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Spectroscopy.pptx food analysis technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Approach and Philosophy of On baking technology
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Cloud computing and distributed systems.
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
Per capita expenditure prediction using model stacking based on satellite ima...
MIND Revenue Release Quarter 2 2025 Press Release
Advanced methodologies resolving dimensionality complications for autism neur...
KodekX | Application Modernization Development
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Review of recent advances in non-invasive hemoglobin estimation
Spectral efficient network and resource selection model in 5G networks
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
The AUB Centre for AI in Media Proposal.docx
Network Security Unit 5.pdf for BCA BBA.
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Spectroscopy.pptx food analysis technology
Unlocking AI with Model Context Protocol (MCP)
20250228 LYD VKU AI Blended-Learning.pptx
Approach and Philosophy of On baking technology
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Cloud computing and distributed systems.
Mobile App Security Testing_ A Comprehensive Guide.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
“AI and Expert System Decision Support & Business Intelligence Systems”

BITS: Introduction to relational databases and MySQL - Schema design

  • 1. Introduction to MySQL ● Introduction ● Installation ● SQL ● Schema design ● Perl BITS/VIB Bioinformatics Training – Jun 29, 2011 – Luc Ducazu <luc@daphnia.com>
  • 2. Database schema ● Although you can execute DDL commands from  the MySQL monitor directly, this is not often  done ● There are tools that allow you to design a schema  graphically and generate the CREATE TABLE ...  statements  ● Examples: – MySQL workbench – Dia
  • 3. MySQL workbench ● Available as a standard package on some Linux  distros (eg Fedora)  ● Available as Windows MSI, Linux DEB or RPM  package or source archive from  http://dev.mysql.com/downloads/workbench/ ● To install a DEB package: # dpkg ­i package.deb ● To install a RPM package: # rpm ­Uvh package.rpm
  • 5. Database schema ● Once the schema is designed, MySQL workbench  can generate a 'script' containing all SQL  statements to create the tables and other objects: File ­>  Export ­>  Forward Engineer SQL CREATE Script ● This 'script' can be executed as usual from the  MySQL monitor
  • 6. Inserting rows ● To populate tables, use the INSERT SQL  statement: mysql> insert into tbl        (col1, col2, ...)         values        (val1, val2, ...) [,        (valx, valy, ...) , ...] ● With: – tbl the name of the table – col1, col2, ... a list (subset) of column names – val1 value for col1 – val2 value for col2
  • 7. Inserting rows ­ examples ● Example (biodb version 1) insert into modorg (id, class, genus, species,  nchr, gsize, draft) values (1, “Bacteria”, “Escherichia”, “coli”,  1, 4.639, “1997­09­05 00:00:00”) ● Note that strings and dates have to be properly  quoted
  • 8. Inserting rows ● You can leave out the column list if – a value is given for all columns – the values are specified in the order dictated by the  schema mysql> insert into tbl        values        (val1, val2, ...) [,        (valx, valy, ...) , ...]
  • 9. Changing rows ● To change one or more rows, use the UPDATE  SQL statement: mysql> update tbl set col1=expr1 [, col2=expr2, ...] [where cond] ● With: – tbl the name of the table – col1 the column to change – expr1 the new value  – cond the row filter ­ if unspecified, all rows of the  table will be updated
  • 10. Changing rows ­ examples ● To change the C elegans number of  chromosomes to 7: update modorg set nchr = 7 where genus = “caenorhabditis”   and species = “elegans”; ● To change the draft date to the current date: update modorg set draft = now();
  • 11. Deleting rows ● To remove rows, you use the DELETE SQL  statement: delete from tbl [where cond] ● With: – tbl the name of the table – cond the row filter ­ if unspecified, all rows of the  table will be deleted – note: since you can only remove entire rows, there is  no need to specify column names
  • 12. Deleting rows ­ examples ● To remove all in model organisms with a genome  publishing date before 2000: delete from modorg where year(draft) < 2000;
  • 13. Introduction to MySQL ● Introduction ● Installation ● SQL ● Schema design ● Perl BITS/VIB Bioinformatics Training – Jun 29, 2011 – Luc Ducazu <luc@daphnia.com>
  • 14. Perl ● Perl is a scripting language that has excellent text  manipulation capabilities ● Many biological 'databases' are available as flat  text files ● Perl is very handy in the automation of the  population of MySQL databases
  • 15. Automated population ● There are basically two ways Perl can help to  insert data into tables: – The Perl script generates USE, INSERT, ... SQL  statements. You can than execute these statements  using the MySQL monitor: $ perl myscript.pl | mysql – The Perl script connects to the database and executes  SQL statements directly: DBI
  • 16. Perl DBI ● Perl DBI provides a programming interface that  abstracts most of the RDBMS specifics ● In principle it should be possible to port scripts,  written for other RDBMS's (like PostgreSQL), to  MySQL with only minimal effort: all you have to  do is change the connection string ● Packages to install (Ubuntu) – libdbi­perl: Perl DBI – libdbd­mysql­perl: MySQL driver for DBI
  • 17. Perl DBI ­ connecting ● Here is a minimal program: #!/usr/bin/perl ­w use strict; use DBI; my $dbh = DBI­>connect(      “DBI:mysql:host=localhost;database=biodb”,      “user”,      “password”) or die; ... $dbh­>disconnect();
  • 18. Perl DBI ­ connecting ● Some highlights: – use DBI; Load Perl DBI library – DBI­>connect(connection string); Connect to a database ● it is a MySQL database server ● the DB server is running on the local machine ● you can provide the name of the database ● you can provide a user name and password The connect() function returns ● a database handle ($dbh) on success ● false on failure – $dbh­>disconnect() to clean up resources
  • 19. Perl DBI  ● To execute a SQL statement that does not return a  result set, eg INSERT, DELETE, use do(): my $n = $dbh­>do(stmt); ● This function – requires a valid database handle – returns the number of rows affected, if no rows are  affected, a special value is returned: 0E0 (evaluates  true) – false in case of an error ● You can use execute() as well
  • 20. Perl DBI  ● To execute a SQL statement that returns a result  set, eg SELECT use the following recipe: 1. Prepare a statement: my $sth = $dbh­>prepare(stmt); 2. Send the query to the database server: $sth­>execute(); 3. Read the result, row by row: my @row = $sth­>fetchrow_array(); my $ref = $sth­>fetchrow_hashref(); 4. Clean up resources: $sth­>finish();
  • 21. Perl DBI ­ examples ● To list all classes in modorg: ... my $qry = “select distinct class ”         . “from modorg ”          . “order by class”; my $sth = $dbh­>prepare($qry); $sth­>execute(); while(my @row = $sth­>fetchrow_array()) {    print “$row[0]n”; }; $sth­>finish(); ...
  • 22. Perl DBI ­ examples ● To list all organisms in modorg: ... my $qry = “select genus, species ”         . “from modorg ”          . “order by genus”; my $sth = $dbh­>prepare($qry); $sth­>execute(); while(my $ref = $sth­>fetchrow_hashref()) {    print $ref­>{“genus”} . “ “         . $ref­>{“species”} . “n”; }; $sth­>finish(); ...
  • 23. Perl DBI ­ examples ● To insert a bunch of rows into modorg: ... my $qry = “insert into modorg ”         . “(id, class, genus, species) ”          . “values (?, ?, ?, ?)”; my $sth = $dbh­>prepare($qry); $sth­>execute(11, “Mammels”,        “Sus”, “scrofa”); ...
  • 24. Quoting ● Never allow arbitrary user input in SQL  statements