MySQL - LabUnix
Transcription
MySQL - LabUnix
MySQL A. Obaid © - Programmation web avancée (INF3005) MySQL 1 Système de gestion de bases de données Un BD est une collection de données Dans une BD relationnelle, les données sont organisées en table Un Système de Gestion de base de données (SGBD) (ou Database Management System-DBMS) est un logiciel qui exploite cette collection des données: – Oracle, PostGres, MySQL,… A. Obaid © - Programmation web avancée (INF3005) MySQL 2 1 1 MySQL MySQL : Un système de bases de données basé sur SQL qui fonctionne en client/serveur SQL (Structured Query Language) est un langage standardisé de requêtes: – Pour l'insertion, la recherche et la mise à jour des données Logiciel libre : www.mysql.com A. Obaid © - Programmation web avancée (INF3005) MySQL 3 Modèle Le serveur MySQL sur une machine distante Permet de manipuler plusieurs BD Permet à plusieurs usagers d'utiliser une même BD MySqld Clients A. Obaid © - Programmation web avancée (INF3005) MySqld BD MySqld Fichiers de la base de données Serveur MySQL 4 2 2 Services offerts par MySQL Connexions au serveur Choix de la BD Create table, Drop, Load Commandes : Select, Insert, Update, Delete Opération de jointure Operations: Count, Like, Order by, Group by Autres: – Sous-requêtes, procédures stockées, triggers, vues … – Administration, optimisation,… A. Obaid © - Programmation web avancée (INF3005) MySQL 5 Stockage des données MySQL stocke plusieurs bases de données en tant que répertoires – Ex: /usr/local/mysql/var/ Chaque table est stockée dans fichier d'un répertoire de la base Pour chaque table, on a: – table.FRM: information sur la structure de la table table.MYD: les données – table.MYI : indexes et statistiques A. Obaid © - Programmation web avancée (INF3005) MySQL 6 3 3 Connexions Commande de connexion: – mysql –h machine –u usager –p [mot-de-passe] – mysql –h machine –u usager La machine peut être locale (localhost) ou distante % mysql –h localhost –u obaiddba –p [mot-de-passe] % mysql -u obaiddba Enter password: ****** Welcome to the MySQL monitor. Commands end with ; or \g. … Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql>… A. Obaid © - Programmation web avancée (INF3005) MySQL 7 Connexions A travers phpMyAdmin – http://moka.labunix.uqam.ca/phpmyadmin/ (etudiants) – http://zeta.labunix.uqam.ca/phpMyAdmin/ A. Obaid © - Programmation web avancée (INF3005) MySQL 8 4 4 Manipulation d'une BD La commande use permet de choisir une BD Une fois la BD choisie, on peut la manipuler avec SQL: – Administration – Manipulation des données Commandes: – Use: choix de la BD – insert into user: ajout d'un usager – Grant: donner des privilèges mysql>use obaid; mysql>insert into user (host, user, password) values (‘localhost’, ‘obaidbda’, password(‘*****’)); mysql>GRANT USAGE ON *.* TO ‘obaiddba’@’localhost‘ IDENTIFIED BY ‘*****’; A. Obaid © - Programmation web avancée (INF3005) MySQL 9 Création de tables CREATE TABLE : permet de créer une table Crée un schéma Il faut désigner une clé primaire – CREATE TABLE NomDeTable (Spécifications des colonnes) CREATE TABLE employe ( Id CHAR(4) NOT NULL nom CHAR(20) NOT NULL, ville CHAR(20), age INT (11) UNSIGNED salaire FLOAT, ); A. Obaid © - Programmation web avancée (INF3005) MySQL 10 5 5 Afficher la structure de la Table On affiche les tables de la BD (avec show tables) describe NomDeTable: affiche la structure de la table (son schéma) mysql>show tables; +-----------------+ | Tables_in_obaid | +-----------------+ | employe | +-----------------+ 1 row in set (0.00 sec) mysql>describe employe; +----------+---------+-----+----+--------+-------+ | Field | Type | Null| Key| Default| Extra | +----------+---------+-----+----+--------+-------+ | IDEmploye| char(4) | YES | | NULL | | | Nom | char(20)| YES | | NULL | | | Ville | char(20)| YES | | NULL | | | Age | int(11) | YES | | NULL | | | Salaire | float | YES | | NULL | | +----------+---------+-----+----+--------+-------+ 5 rows in set (0.04 sec) A. Obaid © - Programmation web avancée (INF3005) MySQL 11 Sélection d'enregistrements SELECT: permet de sélectionner des lignes selon des critères particuliers – SELECT colonnes FROM table(s) WHERE condition select * from employe; +-----------+-------+-----------+------+---------+ | IDEmploye | Nom | Ville | Age | Salaire | +-----------+-------+-----------+------+---------+ | 10 | Bob | Sherbrooke| 37 | 800000 | | 13 | Alice | Laval | 40 | 85000 | | 11 | Alain | Montreal | 35 | 75000 | | 12 | Michel| Sherbrooke| 37 | 80000 | | 14 | Marie | Quebec | 28 | 68000 | +-----------+-------+-----------+------+---------+ 5 rows in set (0.00 sec) A. Obaid © - Programmation web avancée (INF3005) mysql> select Nom,Age from employe; +--------+------+ | Nom | Age | +--------+------+ | Bob | 37 | | Alice | 40 | | Alain | 35 | | Michel | 37 | | Marie | 28 | | Jean | 40 | +--------+------+ 6 rows in set (0.00 sec) MySQL 12 6 6 Ajout d'enregistrements INSERT INTO permet d'ajouter une ligne à une table – INSERT INTO NomDeTable values (Valeur Champ 1, Valeur champ2, …) insert into employee values (15, 'Jean', 'Ottawa', 40,86000); Query OK, 1 row affected (0.01 sec) select * from employee; +-----------+--------+------------+------+---------+ | IDEmploye | Nom | Ville | Age | Salaire | +-----------+--------+------------+------+---------+ | 10 | Bob | Sherbrooke | 37 | 800000 | | 13 | Alice | Laval | 40 | 85000 | | 11 | Alain | Montreal | 35 | 75000 | | 12 | Michel | Sherbrooke | 37 | 80000 | | 14 | Marie | Quebec | 28 | 68000 | | 15 | Jean | Ottawa | 40 | 86000 | +-----------+--------+------------+------+---------+ 6 rows in set (0.00 sec) A. Obaid © - Programmation web avancée (INF3005) MySQL 13 Modifier un enregistrement UPDATE permet de mettre à jour une table existante – UPDATE TABLE set colonne=valeur, colonne=valeur where Condition mysql> update employe set Age=30 where Nom="Bob"; Query OK, 1 row affected (0.02 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from employe; +----------+--------+-----------+------+---------+ | IDEmploye| Nom | Ville | Age | Salaire | +----------+--------+-----------+------+---------+ | 10 | Bob | Sherbrooke| 30 | 800000 | | 13 | Alice | Laval | 40 | 85000 | | 11 | Alain | Montreal | 35 | 75000 | | 12 | Michel | Sherbrooke| 37 | 80000 | | 14 | Marie | Quebec | 28 | 68000 | | 15 | Jean | Ottawa | 40 | 86000 | +----------+--------+-----------+------+---------+ 6 rows in set (0.00 sec) A. Obaid © - Programmation web avancée (INF3005) MySQL 14 7 7 Détruire un enregistrement DELETE FROM permet de détruire un ou plusieurs enregistrements d'une table – DELETE FROM NomDeTable WHERE Condition Attention: – DELETE FROM NomDeTable - Vide toute la table! DROP TABLE : Élimine la table de la BD. A. Obaid © - Programmation web avancée (INF3005) MySQL 15 Détruire un enregistrement mysql> delete from employee where age<30; Query OK, 1 row affected (0.00 sec) mysql> select * from employee; +-----------+--------+------------+------+---------+ | IDEmploye | Nom | Ville | Age | Salaire | +-----------+--------+------------+------+---------+ | 10 | Bob | Sherbrooke | 30 | 800000 | | 13 | Alice | Laval | 40 | 85000 | | 11 | Alain | Montreal | 35 | 75000 | | 12 | Michel | Sherbrooke | 37 | 80000 | | 15 | Jean | Ottawa | 40 | 86000 | +-----------+--------+------------+------+---------+ 5 rows in set (0.01 sec) A. Obaid © - Programmation web avancée (INF3005) MySQL 16 8 8 Chargement de données On peut charger une table à partir d'un fichier texte. – Ca évite de faire de multiples insertions LOAD DATA INFILE permet de charger une table à partir d'un fichier. – LOAD DATA INFILE 'NomDeFichier' into table NomDeTable; Il affecte une ligne de la table par ligne du fichier. Les valeurs des colonnes dans le fichier sont séparées par des caractères TAB (par défaut). A. Obaid © - Programmation web avancée (INF3005) MySQL 17 Chargement de données mysql> create table departement ( IDDep char(4), Nom char(20), Ville char(20) ); load data local infile 'donnees.txt' into table departement; Query OK, 6 rows affected, 18 warnings (0.02 sec) Records: 6 Deleted: 0 Skipped: 0 Warnings: 18 mysql> load data local infile 'donnees.txt' into table departement; Query OK, 6 rows affected (0.00 sec) Records: 6 Deleted: 0 Skipped: 0 Warnings: 0 mysql> select * from departement; +-------+--------------+------------+ | IDDep | Nom | Ville | +-------+--------------+------------+ | DEP1 | Finances | Montreal | | DEP2 | Ingenieurie | Laval | | DEP3 | Comptabilite | Montreal | Fichier: Finances Montreal | DEP4 | Chaussures | Sherbrooke | DEP1 Ingenieurie Laval | DEP5 | Jouets | Quebec | DEP2 Comptabilite Montreal | DEP6 | Informatique | Montreal | DEP3 Chaussures Sherbrooke +-------+--------------+------------+ DEP4 DEP5 Jouets Quebec 6 rows in set (0.00 sec) DEP6 Informatique Montreal A. Obaid © - Programmation web avancée (INF3005) MySQL 18 9 9 Sélection de données mysql> select * from employee where Nom like "A%"; +-----------+-------+----------+------+---------+ | IDEmploye | Nom | Ville | Age | Salaire | +-----------+-------+----------+------+---------+ | 13 | Alice | Laval | 40 | 85000 | | 11 | Alain | Montreal | 35 | 75000 | +-----------+-------+----------+------+---------+ 2 rows in set (0.00 sec) mysql> select IDEmploye, Ville from employee order by ville; +-----------+------------+ | IDEmploye | Ville | mysql> select DISTINCT Ville from employee; +-----------+------------+ +------------+ mysql> select ville, count(*) from employee | 13 | Laval | | Ville | group by ville; | 11 | Montreal | +------------+ +------------+----------+ | 15 | Ottawa | | ville | count(*) | | Sherbrooke | | 10 | Sherbrooke | +------------+----------+ | Laval | | 12 | Sherbrooke | | Laval | 1 | | Montreal | +-----------+------------+ | Montreal | 1 | | Ottawa | 5 rows in set (0.01 sec) | Ottawa | 1 | mysql> select count(Ville) from employee; +--------------+ | count(Ville) | +--------------+ | 5 | +--------------+ 1 row in set (0.00 sec) +------------+ 4 rows in set (0.00 sec) | Sherbrooke | 2 | +------------+----------+ 4 rows in set (0.01 sec) A. Obaid © - Programmation web avancée (INF3005) MySQL 19 Jointure de tables Permettent de sélectionner des informations en croisant plusieurs tables – Select Colonnes from NomDeTable1, NomDeTable2,… where Condition (croisée) mysql> select employe.nom, departement.nom from employee, departement , affectation where employe.IDEmploye=affectation.IDEmploye and departement.IDDep=affectation.IDDep; +--------+--------------+ | nom | nom | +--------+--------------+ | Bob | Finances | | Michel | Finances | | Alice | Ingenieurie | | Alain | Chaussures | | Jean | Informatique | +--------+--------------+ A. Obaid © - Programmation web avancée (INF3005) MySQL 20 10 10 Jointure de tables mysql> select * from employe; +----------+-------+-----------+-----+--------+ | IDEmploye| Nom | Ville | Age | Salaire| +----------+-------+-----------+-----+--------+ | 10 | Bob | Sherbrooke| 30| 800000| | 13 | Alice | Laval | 40| 85000| | 11 | Alain | Montreal | 35| 75000| | 12 | Michel| Sherbrooke| 37| 80000| | 15 | Jean | Ottawa | 40| 86000| +----------+-------+-----------+-----+--------+ 5 rows in set (0.00 sec) Employe affectation annees Departement mysql> select * from departement; +-------+-------------+-----------+ | IDDep | Nom | Ville | +-------+-------------+-----------+ | DEP1 | Finances | Montreal | | DEP2 | Ingenieurie | Laval | | DEP3 | Comptabilite| Montreal | | DEP4 | Chaussures | Sherbrooke| | DEP5 | Jouets | Quebec | | DEP6 | Informatique| Montreal | +-------+-------------+-----------+ 6 rows in set (0.00 sec) mysql> select * from affectation; +-----------+-------+--------+ | IDEmploye | IDDep | Annees | +-----------+-------+--------+ | 10 | DEP1 | 10 | | 12 | DEP1 | 20 | | 13 | DEP2 | 10 | | 15 | DEP6 | 5 | | 11 | DEP4 | 13 | +-----------+-------+--------+ 5 rows in set (0.00 sec) A. Obaid © - Programmation web avancée (INF3005) MySQL 21 Commandes SQL en PHP La méthode mysql_query() invoque une commande SQL. Le nombre d'arguments dépend de la commande SQL. – Pour SELECT, un seul argument : Chaine de caractères qui contient la requête, Retourne un résultat dans une variable PHP qu'on pourra parcourir $resultat = mysql_query("SELECT Nom, Salaire FROM Employes"); A. Obaid © - Programmation web avancée (INF3005) MySQL 22 11 11 Connexion avec PHP mysql_connect(Serveur, usager, MotDePasse) connecte à une BD distante Ramène un identificateur de la connexion ou une valeur vide si la connexion n’a pas pu être établie <!-- connection.php --> <?php $connexion = mysql_connect("localhost","xxxxxxx","xxxxxxx"); if (!$connexion) { exit('Connexion impossible'); } else { echo "Connexion reussie <br />"; } ?> A. Obaid © - Programmation web avancée (INF3005) MySQL 23 Creation d'une BD avec PHP On utilise la fonction mysql_query() à laquelle on fournit comme premier argument la commande CREATE DATABASE et comme deuxième l'objet Connexion. – mysql_query("CREATE DATABASE BD", $connexion) Avant de commencer à exécuter des requêtes sur une base de données, on doit la sélectionner la BD à utiliser mysql_select_db(). A. Obaid © - Programmation web avancée (INF3005) MySQL 24 12 12 Création d'une table Utiliser mysql_query() dans laquelle on utilise la commande SQL: – CREATE TABLE nomDeLaTable ( nomDeCollonne1 nomDeCollonne2 Type,… ) Type, $requeteSQL="CREATE TABLE Employe { IDEmploye int not null auto increment Nom varchar(20) not null, Ville varchar(20) not null, Age int, Salaire Float primary key ( id ); }" ; mysql_query($requeteSQL,$connexion); A. Obaid © - Programmation web avancée (INF3005) MySQL 25 Création d'une table avec PHP <!-- MYSQL/createtable.php --> <?php $connexion = mysql_connect("localhost","obaiddba","Ab.0ba1d"); if (!$connexion) { die('Connexion impossible'); } $requeteSQL="create table departements ( id int not null auto_increment, Nom varchar(20) not null, Ville varchar(20) not null, primary key ( id ) )"; mysql_select_db("obaid", $connexion); $resultat= mysql_query($requeteSQL); if (! $resultat) { $message = 'Requete invalide: ' . mysql_error() . "\n"; die($message); } mysql_close($connexion); ?> A. Obaid © - Programmation web avancée (INF3005) MySQL 26 13 13 Exécution de commandes SQL On utilise la commande mysql_query() en lui fournissant une requête SELECT, UPDATE, INSERT,… – $resultat = mysql_query("SELECT Nom, Ville FROM Compagnie"); Cette commande ramène un ensemble de valeurs que l'on peut stocker dans une variable de type tableau . A. Obaid © - Programmation web avancée (INF3005) MySQL 27 Parcours des résultats des commandes SQL On parcourt le tableau des résultats d'une requête en utilisant la fonction mysql_fetch_array(): – $uneLigne = mysql_fetch_array($resultat); Cette fonction retourne une ligne à la fois. Chaque ligne est structurée comme un tableau associatif dont les clés sont les attributs spécifiés dans la commande. A. Obaid © - Programmation web avancée (INF3005) MySQL 28 14 14 Parcours des résultats des commandes SQL – État brut Le résultat brut d’un requête SQL est retourné sous form d’un tableau associatif ! <!-- requeteRaw.php --> <?php $connexion = mysql_connect("localhost","obaiddba","Ab.0ba1d"); if (!$connexion) { exit('Connexion impossible'); } mysql_select_db("obaid", $connexion); $requeteSQL="SELECT * from employes" ; $resultat= mysql_query($requeteSQL); echo "<pre>"; print_r( mysql_fetch_array($resultat)); echo "</pre>"; mysql_close($connexion); ?> A. Obaid © - Programmation web avancée (INF3005) MySQL 29 Parcours des résultats des commandes SQL <?php $connexion = mysql_connect("localhost","obaiddba","Ab.0ba1d"); if (!$connexion) { exit('Connexion impossible'); } mysql_select_db("obaid", $connexion); $requeteSQL="SELECT Nom, Ville, Salaire from employes" ; $resultat= mysql_query($requeteSQL); echo "<h4> Liste des employés </h4>" ; echo "<table>"; echo "<th>Nom<th>Ville<th>Salaire<tr>"; while($uneLigne = mysql_fetch_array($resultat)) { echo "<td>".$uneLigne['Nom']."<td>".$uneLigne['Ville']."<td>".$uneLigne['Salaire‘ ]."<tr>"; } echo "</table>"; mysql_close($connexion); ?> A. Obaid © - Programmation web avancée (INF3005) MySQL 30 15 15 Affichage des résultats <!– Fichier: requete2.php --> <html> mysql_select_db("obaid", $connexion); <head> $requeteSQL="SELECT * from employee" ; <?php $resultat= mysql_query($requeteSQL); $style=<<<EOM <style type="text/css"> echo "<table border=\"4\">"; td, th {color:white ; echo "<th> Nom </th><th>Habite</th>" ; background:blue; while($uneLigne = mysql_fetch_array($resultat)) { } echo "<tr><td>". $uneLigne['Nom']."</td><td>".$uneLigne['Ville']."</td>"; </style> } EOM; echo "</table>"; echo "$style \n"; mysql_close($connexion); ?> ?> </head> </body> <body> </html> <?php $connexion = mysql_connect("localhost","obaiddba","Ab.0ba1d"); if (!$connexion) { exit('Connexion impossible'); } A. Obaid © - Programmation web avancée (INF3005) MySQL 31 Insertion d’éléments <!-- Fichier: MYSQL/insert1.html --> <html> <body> <h4> Forumulaire d'ajout d'un départemenet </h4> <form id="f1" action="insert1.php" method="get"> Entrez le nom et la ville du nouveau département<br/> Nom: <input type="text" name="nom"><br/> Ville: <input type="text" name="ville"><br/> <input type="submit" value="Insérer" ><br/> </form> </body> <!-- MYSQL/insert1.php --> </html> <?php $Nom=$_GET['nom' ]; $Ville=$_GET['ville']; $connexion = mysql_connect("localhost","obaiddba","Ab.0ba1d"); if (!$connexion) { die('Connexion impossible');} $requeteSQL = "insert into departements (Nom, Ville) values ". "('$Nom', '$Ville')"; mysql_select_db("obaid", $connexion); $resultat= mysql_query($requeteSQL); if (! $resultat) die("Resultat: ".mysql_error()); mysql_close($connexion); ? A. Obaid © - Programmation web avancée (INF3005) MySQL 32 16 16 Insertion d’éléments <!-- Fichier: MYSQL/insereListe.html --> <html> <body> <h4> Forumulaire d'ajout d'un employé </h4> <form id="f1" action="insereListe.php" method="POST"> Veuillez saisir les informations ci-dessous<br/> <table> <td> Nom: <td> <input type="text" name="nom"><tr> <td>Ville:<td> <input type="text" name="ville"><tr> <td>Age: <td> <input type="text" name="age"><tr> <td>Salaire: <td> <input type="text" name="salaire"><tr> <td><input type="submit" value="Insérer" ><tr> </table> </form> </body> </html> A. Obaid © - Programmation web avancée (INF3005) MySQL 33 Mise à jour d’une table avec PHP <!-- maj.php --> <?php $connexion = mysql_connect("localhost","obaiddba","Ab.0ba1d"); if (!$connexion) { die('Connexion impossible: ' . mysql_error()); } mysql_select_db("obaid", $connexion); mysql_query("UPDATE employes SET Age=26 WHERE Nom = 'Alain'"); mysql_close($connexion); ?> A. Obaid © - Programmation web avancée (INF3005) MySQL 34 17 17